标签:style blog http color io art
ManualResetEvent reviceManager = new ManualResetEvent(false);
1 public void args_Completed(object sender, SocketAsyncEventArgs e) 2 { 3 //监听完成客户端的请求,一但监听到返回新的套接字 4 var clientSocket = e.AcceptSocket; 5 //启动线程获取客户端发来的消息 6 if (clientSocket == null) return; 7 8 //这部分为接收消息 9 var t = new Thread(GetClientMsg); 10 //设置线程为后台线程 11 t.IsBackground = true; 12 //启动线程 13 t.Start(clientSocket); 14 //显示信息 15 ShowMsg(clientSocket.RemoteEndPoint + "上线了"); 16 //将事件状态设置为终止状态,允许一个或多个等待线程继续 17 manager.Set(); 18 }
建议对照 C# Socket基础(一)之启动异步服务侦听 来看。
1 private void GetClientMsg(object socket) 2 { 3 var socketClient = socket as Socket; 4 if (socketClient == null) return; 5 while (true) 6 { 7 try 8 { 9 reviceManager.Reset(); 10 var bytes = new byte[1024 * 1024 * 4]; 11 var receiveArgs = new SocketAsyncEventArgs();
//设置缓冲区 12 receiveArgs.SetBuffer(bytes, 0, bytes.Length); 13 receiveArgs.Completed += receiveArgs_Completed;
//开始异步接收 14 socketClient.ReceiveAsync(receiveArgs); 15 reviceManager.WaitOne(); 16 } 17 catch (Exception ex) 18 { 19 20 //显示异常消息 21 ShowMsg(ex.Message);
22 }
}
}
接收消息完成回调事件
1 void receiveArgs_Completed(object sender, SocketAsyncEventArgs e) 2 { 3 var socketClient = sender as Socket; 4 var bytes = e.Buffer; 5 ShowMsg(socketClient.RemoteEndPoint + "说:" + System.Text.Encoding.UTF8.GetString(bytes)); 6 reviceManager.Set(); 7 }
待续。下一篇:Socket基础(三)之客户端和服务器建立连接和接收消息
C# Socket基础(二) 之 服务器异步接收消息,布布扣,bubuko.com
标签:style blog http color io art
原文地址:http://www.cnblogs.com/gaobing/p/3860178.html