標籤: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基礎(三)之用戶端和伺服器建立串連和接收訊息
gaobing 出處: http://gaobing.cnblogs.com 提示:本文著作權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。