C# UdpClient使用Receive和BeginReceive接收訊息時的不同寫法

來源:互聯網
上載者:User

標籤:style   blog   color   使用   io   re   

使用Receive(同步阻塞方式), 注意使用同步方法時,需要使用線程來開始方法,不然會使UI介面卡死

            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 5858);            UdpClient udpClient = new UdpClient(RemoteIpEndPoint);            while (true) //由於Receive方法是阻塞方法,一個Receive操作完了後才能繼續往下執行,所以能在這裡使用死迴圈            {                Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);                string msg = Encoding.UTF8.GetString(receiveBytes);            }

 

使用BeginReceive(非同步)

 

               private static void InitializeUdpClient()
              {               
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 5858); UdpClient udpClient = new UdpClient(RemoteIpEndPoint); //如果這裡寫while(true) 則會不停掛起非同步接收操作,直到佔滿緩衝區間或隊列。會報“由於系統緩衝區空間不足或隊列已滿,不能執行通訊端上的操作”的錯 UdpState s = new UdpState(udpClient, RemoteIpEndPoint); udpClient.BeginReceive(EndReceive, s); } private static void EndReceive(IAsyncResult ar) { try { UdpState s = ar.AsyncState as UdpState; if (s != null) { UdpClient udpClient = s.UdpClient; IPEndPoint ip = s.IP; Byte[] receiveBytes = udpClient.EndReceive(ar, ref ip); string msg = Encoding.UTF8.GetString(receiveBytes); udpClient.BeginReceive(EndReceive, s);//在這裡重新開始一個非同步接收,用於處理下一個網路請求 } } catch (Exception ex) { //處理異常 } } public class UdpState { private UdpClient udpclient = null; public UdpClient UdpClient { get { return udpclient; } } private IPEndPoint ip; public IPEndPoint IP { get { return ip; } } public UdpState(UdpClient udpclient, IPEndPoint ip) { this.udpclient = udpclient; this.ip = ip; } }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.