写的也很简单,自己觉得挺有意思了
程序如图
主要代码
public class Message { Form1 mainfrom = null; public Message() { } public Message(Form1 form) { mainfrom = form; } public bool StartReceive(int port) { try { IPEndPoint iep = new IPEndPoint(IPAddress.Loopback, port); Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpServer.Bind(iep); tcpServer.Listen(100); tcpServer.BeginAccept(new AsyncCallback(Accept), tcpServer); return true; } catch (Exception ex) { return false; } } private void Accept(IAsyncResult ia) { Socket socket = ia.AsyncState as Socket; var client = socket.EndAccept(ia); byte[] buf = new byte[1024]; socket.BeginAccept(new AsyncCallback(Accept), socket); StateObject state = new StateObject(); state.workSocket = client; try { client.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(Receive), state); } catch (Exception ex) { //Console.WriteLine("监听请求时出错: " + ex.ToString()); } } private void Receive(IAsyncResult ia) { StateObject state = ia.AsyncState as StateObject; if (state == null) { return; } Socket client = state.workSocket; if (client == null) { return; } try { int count = client.EndReceive(ia); if (count > 0) { try { client.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(Receive), client); string context = Encoding.GetEncoding("gb2312").GetString(state.buffer, 0, count); //显示接收消息 mainfrom.LoginFormTextChange(context); } catch (Exception ex) { //Console.WriteLine("接收的数据出错: {0}", ex.ToString()); } } } catch (Exception err) { } } public void SendMessage(int port, string m) { System.Text.Encoding CharSet = System.Text.Encoding.GetEncoding("gb2312"); Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { tcpClient.Connect(IPAddress.Loopback, port); string sendmsg = m; byte[] buff = CharSet.GetBytes(sendmsg); tcpClient.Send(buff, buff.Length, 0); } catch (SocketException e) { } } } public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); }