C# UdpClient使用Receive和BeginReceive接收消息时的不同写法

使用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; } }

 

posted @ 2014-07-10 14:28  逍遥子k  阅读(4775)  评论(0编辑  收藏  举报