博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
硬件UDP读数AsynUdpClient
阅读量:5144 次
发布时间:2019-06-13

本文共 9419 字,大约阅读时间需要 31 分钟。

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; } } }}
View Code

调用

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

 

转载于:https://www.cnblogs.com/zengtianli/p/11139869.html

你可能感兴趣的文章
Hive(7)-基本查询语句
查看>>
Redis快速入门
查看>>
注意java的对象引用
查看>>
C++ 面向对象 类成员函数this指针
查看>>
inline函数的总结
查看>>
SPSS-生存分析
查看>>
【Jquery】$.Deferred 对象
查看>>
Python字符编码
查看>>
leetcode 49. 字母异位词分组(Group Anagrams)
查看>>
NSPredicate的使用,超级强大
查看>>
自动分割mp3等音频视频文件的脚本
查看>>
财务结算的目的和一般流程
查看>>
Myeclipse 优化1
查看>>
[BJOI2012]最多的方案(记忆化搜索)
查看>>
生成了一个严重警告并将其发送到远程终结点。这会导致连接终止。TLS 协议所定义的严重错误代码是...
查看>>
判断字符串是否为空的注意事项
查看>>
布兰诗歌
查看>>
vscode 中 eslint 相关配置
查看>>
老李分享:5个衡量软件质量的标准
查看>>
Xcode部分插件无法使用识别的问题
查看>>