C#中 B/S模式和C/S模式进行通讯----Socket通讯

I)背景:

      在很多系统中即包含B/S架构也包括C/S架构,这就涉及到B/S与C/S进行通讯的问题,关于这个问题我也在CSDN的论坛中专门拿出来

  和各位的高手进行了讨论,具体的帖子:http://topic.csdn.net/u/20100326/09/dd9ee3ce-3d90-4583-8eaf-d8542d7eec72.html

总的来说,提供了两种解决方案:

       1)通过WebService进行通讯 。      2)通过WCF进行通讯

但是关于WebService和WCF的知识懂的不太多,于是从另外一个方法进行了考虑,使用Socket进行通讯。

II)服务器端的测试代码:

private bool islistening = false; private void button1_Click(object sender, EventArgs e) { if (!islistening) { //创建一个TCP/IP Socket用于监听客户端连接 Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); int port = 8000; String host = "192.168.1.222";//连接网络时使用的Ip地址 //string host = "127.0.0.1";//在不连接网络时使用 IPHostEntry entry = Dns.GetHostEntry(host); IPAddress ip = entry.AddressList[0]; 先绑定要监听的主机和端口 , 使 Socket 与一个本地终结点相关联。 listenSocket.Bind(new IPEndPoint(ip, port)); //再开始监听,并且指定监听队列的最大长度 listenSocket.Listen(10); islistening = true; //线程将一直阻塞直到有新的客户端连接 listenSocket.BeginAccept(new AsyncCallback(this.OnAcceptSocket), null); AddMsg("开始侦听..."); //生成主线程、启动主线程 Thread tMain = new Thread(new ThreadStart(TestMainRepart)); tMain.Start(); } else { MessageBox.Show("服务已开启!"); } }

 


private void OnAcceptSocket(IAsyncResult ar) { if (!islistening) return; Socket s = listenSocket.EndAccept(ar); MySocket socket = new MySocket(); socket.Socket = s; socket.IsConnected = true; socket.Socket.BeginReceive(socket.Buffer, 0, MySocket.BufSize, SocketFlags.None, new AsyncCallback(this.OnReceiveData), socket); listenSocket.BeginAccept(new AsyncCallback(this.OnAcceptSocket), null); }

 

 


private void OnReceiveData(IAsyncResult ar) { MySocket socket = ar.AsyncState as MySocket; if (socket == null || !socket.IsConnected) return; int length = socket.Socket.EndReceive(ar); //msg为接受的数据 string msg = Encoding.UTF8.GetString(socket.Buffer,0,length); //将接受的数据再发送到客户端 socket.Send(msg ); }

 


public class MySocket { private Socket socket; private bool isConnected; private byte[] buf; private string clientName; public const int BufSize = 8192; public const string ExitCode = "EXIT"; public MySocket(string clientName, Socket socket, byte[] buf) { this.clientName = clientName; this.socket = socket; this.buf = buf; this.isConnected = false; } public MySocket(string clientName, Socket socket) : this(clientName, socket, new byte[BufSize]) { } public MySocket(string clientName) : this(clientName, new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { } public MySocket() { this.buf = new byte[BufSize]; } public Socket Socket { get { return socket; } set { socket = value; } } public bool IsConnected { get { return isConnected; } set { isConnected = value; } } public string ClientName { get { return clientName; } set { clientName = value; } } public byte[] Buffer { get { return buf; } } public void SendMessage(string msg) { byte[] buf = Encoding.UTF8.GetBytes(msg); socket.BeginSend(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(SendCallBack), socket); } public void SendCallBack(IAsyncResult ir) { try { Socket socket = (Socket)ir.AsyncState; socket.EndSend(ir); } catch { } } }

 

 

 

III)客户端代码:

 

protected void Button1_Click(object sender, EventArgs e) { int port = 8000; string host = "192.168.1.222"; //string host = "127.0.0.1"; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); c.Connect(ipe); string str = "要发送的数据"; byte[] bs = Encoding.UTF8.GetBytes(str ); //发送数据 c.Send(bs, bs.Length, 0); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = c.Receive(recvBytes, recvBytes.Length, 0); //recvStr为接受到的数据 recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes); c.Close(); }

 

IV)参考的例子:

     http://blog.csdn.net/zhoufoxcn/archive/2009/03/18/4000301.aspx

     http://blog.csdn.net/lyd_253261362/archive/2009/07/30/4394370.aspx

你可能感兴趣的:(.net)