/// <summary> /// 开始异步接收数据 /// </summary> /// <param name="key">要接收的客户端的ip地址和端口号</param> private void ReceiveAsync(string key) { doReceive.Reset(); if (ListClient.ContainsKey(key)) { UdpClient client = ListClient[key]; //if (!client.Connected) //{ // ListClient.Remove(key); // OnComplete(key, EnSocketAction.Close); // return; //} UdpStateObject obj = new UdpStateObject { Client = client }; try { client.Client.BeginReceive(obj.ListData, 0, obj.ListData.Length, SocketFlags.None, ReceiveCallBack, obj); } catch (Exception) { } doReceive.WaitOne(); } }
/// <summary> /// 异步接收消息的回调函数 /// </summary> /// <param name="ar"></param> private void ReceiveCallBack(IAsyncResult ar) { UdpStateObject obj = ar.AsyncState as UdpStateObject; int count = -1; try { count = obj.Client.Client.EndReceive(ar); doReceive.Set(); } catch (Exception) { //如果发生异常,说明客户端失去连接,触发关闭事件 Close(); OnComplete(obj.Client, EnSocketAction.Close); } if (count > 0) { string msg = Encoding.UTF8.GetString(obj.ListData, 0, count); if (!string.IsNullOrEmpty(msg)) { if (Received != null) { IPEndPoint iep = obj.Client.Client.RemoteEndPoint as IPEndPoint; string key = string.Format("{0}:{1}", iep.Address, iep.Port); Received(key, msg); } } } }
/// <summary> /// 异步接收消息 /// </summary> private void ReceiveAsync() { doReceive.Reset(); UdpStateObject obj = new UdpStateObject { Client = client }; client.Client.BeginReceive(obj.ListData, 0, obj.ListData.Length, SocketFlags.None, ReceiveCallBack, obj); doReceive.WaitOne(); }
public static void StartListeningUDP() { // Receive a message and write it to the console. IPEndPoint EndPoint = new IPEndPoint(IPAddress.Any, 8080); UdpClient Client = new UdpClient(EndPoint); UdpStateObject Net = new UdpStateObject(); Net.endPoint = EndPoint; Net.client = Client; // Do some work while we wait for a message. while (true) { messageReceived = false; //Console.WriteLine("Waiting for UDP conection..."); Client.BeginReceive(new AsyncCallback(ReceiveCallbackUDP), Net); while (!messageReceived) { // Do something //Thread.Sleep(16); } } }
/// <summary> /// 异步接收数据的回调函数 /// </summary> /// <param name="ar"></param> private void ReceiveCallBack(IAsyncResult ar) { UdpStateObject obj = ar.AsyncState as UdpStateObject; int count = -1; try { count = obj.Client.Client.EndReceive(ar); } catch (Exception) { if (!obj.Client.Client.Connected) { IPEndPoint iep = obj.Client.Client.RemoteEndPoint as IPEndPoint; string key = string.Format("{0}:{1}", iep.Address.ToString(), iep.Port); ListClient.Remove(key); OnComplete(key, EnSocketAction.Close); doReceive.Set(); return; } } doReceive.Set(); if (count > 0) { string msg = Encoding.UTF8.GetString(obj.ListData, 0, count); if (!string.IsNullOrEmpty(msg)) { if (Received != null) { IPEndPoint iep = obj.Client.Client.RemoteEndPoint as IPEndPoint; string key = string.Format("{0}:{1}", iep.Address.ToString(), iep.Port); Received(key, msg);//触发接收事件 } } } }