public class AsynUdpClient { ////// 回调委托 /// /// ip /// public delegate void UdpReciveHandler(EndPoint point, string msg); //Socket服务 private readonly Socket _server; //是否发送成功 public bool IsSuccess = false; ////// 发送结果消息 /// public string ResultMsg = ""; ////// 构造方法 /// /// 客户端端口号 public AsynUdpClient(int port = 12345) { _server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); var ips = Dns.GetHostAddresses(Dns.GetHostName()); var firstOrDefault = ips.FirstOrDefault(o => o.AddressFamily == AddressFamily.InterNetwork); var ip4 = "127.0.0.1"; if (firstOrDefault != null) { ip4 = firstOrDefault.ToString(); } _server.Bind(new IPEndPoint(IPAddress.Parse(ip4), port)); //绑定端口号和IP } ////// 向特定ip的主机的端口发送数据报 /// /// ip+端口号 /// 发送文本数据 /// public void SendMsg(string address, string msg,UdpReciveHandler udpReciveEvent) { lock (this) { IsSuccess = false; try { var arr = address.Split(':').ToList(); if (arr.Count == 1) { arr.Add("12345"); } EndPoint point = new IPEndPoint(IPAddress.Parse(arr[0]), Convert.ToInt32(arr[1])); var bytes = HexStringToBytes(msg); _server.SendTo(bytes, point);//00 B0 D0 7B BC 21 _server.SendTimeout = 500; IsSuccess = true; ResultMsg = "发送成功:" + msg; //等待 Thread.Sleep(200); Task.Factory.StartNew(() => { ExecReciveMsg(udpReciveEvent); }); } catch (Exception ex) { IsSuccess = false; ResultMsg = "发送失败!" + ex.Message; } } } ////// 回调 /// ///private void ExecReciveMsg(UdpReciveHandler udpReciveEvent) { EndPoint point = new IPEndPoint(IPAddress.Any, 12345); //用来保存发送方的ip和端口号 byte[] buffer = new byte[1024]; int length = _server.ReceiveFrom(buffer, ref point); //接收数据报 var rebuffer = new byte[length]; for (var i = 0; i < length; i++) { rebuffer[i] = buffer[i]; } var msg = BytesToHexString(rebuffer,' '); //委托回调 if (udpReciveEvent != null) udpReciveEvent(point, msg); } //解析列表 private static readonly List HexCharList = new List (){ '0','1','2','3','4','5','6', '7','8','9','A','B','C', 'D','E','F'}; /// /// 字符串转字节 /// /// 转化字符串 ///An array of bytes private byte[] HexStringToBytes(string hex) { try { hex = hex.ToUpper(); MemoryStream memoryStream = new MemoryStream(); for (int index = 0; index < hex.Length; ++index) { if (index + 1 < hex.Length && (HexCharList.Contains(hex[index]) && HexCharList.Contains(hex[index + 1]))) { memoryStream.WriteByte( (byte) (HexCharList.IndexOf(hex[index])*16 + HexCharList.IndexOf(hex[index + 1]))); ++index; } } byte[] array = memoryStream.ToArray(); memoryStream.Dispose(); return array; } catch (Exception ex) { throw ex; } } ////// 字节转换成字符串 /// /// An array of bytes /// ///Hex string private string BytesToHexString(byte[] bytes, char segment) { try { StringBuilder stringBuilder = new StringBuilder(); foreach (byte inByte in bytes) { if ((int)segment == 0) stringBuilder.Append(string.Format("{0:X2}", (object)inByte)); else stringBuilder.Append(string.Format("{0:X2}{1}", (object)inByte, (object)segment)); } if ((int)segment != 0 && stringBuilder.Length > 1 && (int)stringBuilder[stringBuilder.Length - 1] == (int)segment) stringBuilder.Remove(stringBuilder.Length - 1, 1); return stringBuilder.ToString(); } catch (Exception ex) { throw ex; } } }}
调用
private static readonly AsynUdpClient UdpClient = new AsynUdpClient(Convert.ToInt32(UdpClientPort));
UdpClient.SendMsg(item.deviceip, code, (point, msg) => { UdpClientRecive(point, msg,devicemac); }); if (UdpClient.IsSuccess) { LogHelper.Debug("发送:" + code); }
////// 报文回复回调 /// /// /// /// public void UdpClientRecive(EndPoint point, string msg, string devicemac) { //其他操作 }
public class AsynUdpClient { /// <summary> /// 回调委托 /// </summary> /// <param name="point">ip</param> /// <param name="msg"></param> public delegate void UdpReciveHandler(EndPoint point, string msg); //Socket服务 private readonly Socket _server; //是否发送成功 public bool IsSuccess = false; /// <summary> /// 发送结果消息 /// </summary> public string ResultMsg = "";
/// <summary> /// 构造方法 /// </summary> /// <param name="port">客户端端口号</param> public AsynUdpClient(int port = 12345) { _server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); var ips = Dns.GetHostAddresses(Dns.GetHostName()); var firstOrDefault = ips.FirstOrDefault(o => o.AddressFamily == AddressFamily.InterNetwork); var ip4 = "127.0.0.1"; if (firstOrDefault != null) { ip4 = firstOrDefault.ToString(); } _server.Bind(new IPEndPoint(IPAddress.Parse(ip4), port)); //绑定端口号和IP } /// <summary> /// 向特定ip的主机的端口发送数据报 /// </summary> /// <param name="address">ip+端口号</param> /// <param name="msg">发送文本数据</param> /// <param name="udpReciveEvent"></param> public void SendMsg(string address, string msg,UdpReciveHandler udpReciveEvent) { lock (this) { IsSuccess = false; try { var arr = address.Split(':').ToList(); if (arr.Count == 1) { arr.Add("12345"); } EndPoint point = new IPEndPoint(IPAddress.Parse(arr[0]), Convert.ToInt32(arr[1])); var bytes = HexStringToBytes(msg); _server.SendTo(bytes, point);//00 B0 D0 7B BC 21 _server.SendTimeout = 500; IsSuccess = true; ResultMsg = "发送成功:" + msg; //等待 Thread.Sleep(200); Task.Factory.StartNew(() => { ExecReciveMsg(udpReciveEvent); }); } catch (Exception ex) { IsSuccess = false; ResultMsg = "发送失败!" + ex.Message; } } } /// <summary> /// 回调 /// </summary> /// <returns></returns> private void ExecReciveMsg(UdpReciveHandler udpReciveEvent) { EndPoint point = new IPEndPoint(IPAddress.Any, 12345); //用来保存发送方的ip和端口号 byte[] buffer = new byte[1024]; int length = _server.ReceiveFrom(buffer, ref point); //接收数据报 var rebuffer = new byte[length]; for (var i = 0; i < length; i++) { rebuffer[i] = buffer[i]; } var msg = BytesToHexString(rebuffer,' '); //委托回调 if (udpReciveEvent != null) udpReciveEvent(point, msg); } //解析列表 private static readonly List<char> HexCharList = new List<char>(){'0','1','2','3','4','5','6', '7','8','9','A','B','C', 'D','E','F'}; /// <summary> /// 字符串转字节 /// </summary> /// <param name="hex">转化字符串</param> /// <returns>An array of bytes</returns> private byte[] HexStringToBytes(string hex) { try { hex = hex.ToUpper(); MemoryStream memoryStream = new MemoryStream(); for (int index = 0; index < hex.Length; ++index) { if (index + 1 < hex.Length && (HexCharList.Contains(hex[index]) && HexCharList.Contains(hex[index + 1]))) { memoryStream.WriteByte( (byte) (HexCharList.IndexOf(hex[index])*16 + HexCharList.IndexOf(hex[index + 1]))); ++index; } } byte[] array = memoryStream.ToArray(); memoryStream.Dispose(); return array; } catch (Exception ex) { throw ex; } } /// <summary> /// 字节转换成字符串 /// </summary> /// <param name="bytes">An array of bytes</param> /// <param name="segment"></param> /// <returns>Hex string</returns> private string BytesToHexString(byte[] bytes, char segment) { try { StringBuilder stringBuilder = new StringBuilder(); foreach (byte inByte in bytes) { if ((int)segment == 0) stringBuilder.Append(string.Format("{0:X2}", (object)inByte)); else stringBuilder.Append(string.Format("{0:X2}{1}", (object)inByte, (object)segment)); } if ((int)segment != 0 && stringBuilder.Length > 1 && (int)stringBuilder[stringBuilder.Length - 1] == (int)segment) stringBuilder.Remove(stringBuilder.Length - 1, 1); return stringBuilder.ToString(); } catch (Exception ex) { throw ex; } } }}