C# Socket基礎(二) 之 伺服器非同步接收訊息

來源:互聯網
上載者:User

標籤: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 提示:本文著作權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.