/// <summary> /// UDP默认使用任何可用端口 /// </summary> /// <param name="networkInterfacesIp"></param> /// <param name="error"></param> /// <param name="localPort"></param> /// <returns></returns> public bool Bind(string networkInterfacesIp, out string error, Int32 localPort = 0) { Boolean result = false; try { error = null; NCIp = networkInterfacesIp; var ip = IPAddress.Any; if (!string.IsNullOrEmpty(networkInterfacesIp)) { ip = IPAddress.Parse(networkInterfacesIp); } client = new UdpClient(new IPEndPoint(ip, localPort)); UdpState state = new UdpState(client, RemoteEP); client.BeginReceive(EndReceive, state); result = true; IsConnected = true; } catch (SocketException ex) { error = string.Format("初始化网络时发生了如下错误:\r\n\r\n\t{0}", ex.Message); } return(result); }
/// <summary> /// 接收数据回调处理程序 /// </summary> /// <param name="ar"></param> void EndReceive(IAsyncResult ar) { UdpState s = ar.AsyncState as UdpState; if (s != null) { UdpClient udpClient = s.UdpClient; IPEndPoint ip = s.IP; Byte[] receiveBytes; string error; try { receiveBytes = udpClient.EndReceive(ar, ref ip); } catch (ObjectDisposedException) { //如果是手动Close就直接返回 return; } catch (System.Exception ex) { //如果是网络环境异常,就释放掉当前连接 System.Diagnostics.Trace.WriteLine(ex.Message); //Logger.Error(String.Format("UDP EndReceive报错:{0}", ex.Message)); //CloseInternal(udpClient); Close(out error); return; } PrintDataSourceEndPoint(ip); OnDataReceived(receiveBytes); try { udpClient.BeginReceive(EndReceive, s); //在这里重新开始一个异步接收,用于处理下一个网络请求 } catch (ObjectDisposedException) { Close(out error); } } }