標籤: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; } }