| | |
| | | /// <summary> |
| | | /// 线程:不断监听UDP报文 |
| | | /// </summary> |
| | | static Thread thrRecv; |
| | | static Task thrRecv; |
| | | |
| | | public static void StartReceive() |
| | | { |
| | | var receiveIp = "127.0.0.1"; |
| | | var receivePort = 53490; |
| | | var config = Helpers.Tool.GetSystemConfig().baseSysConfg; |
| | | if (config != null) |
| | | { |
| | | if (!string.IsNullOrWhiteSpace(config.receiveIp)) |
| | | { |
| | | receiveIp = config.receiveIp; |
| | | } |
| | | if (!string.IsNullOrWhiteSpace(config.receivePort)) |
| | | { |
| | | int.TryParse(config.toPort, out receivePort); |
| | | } |
| | | } |
| | | if (!IsUdpcRecvStart) // 未监听的情况,开始监听 |
| | | { |
| | | localIpep = new IPEndPoint(IPAddress.Parse("192.168.2.111"), 53490); // 本机IP和监听端口号 |
| | | localIpep = new IPEndPoint(IPAddress.Parse(receiveIp), receivePort); // 本机IP和监听端口号 |
| | | udpcRecv = new UdpClient(localIpep); |
| | | thrRecv = new Thread(ReceiveMessage); |
| | | thrRecv = new Task(() => { ReceiveMessage(); }); |
| | | thrRecv.Start(); |
| | | IsUdpcRecvStart = true; |
| | | Console.WriteLine("UDP监听器已成功启动"); |
| | |
| | | { |
| | | if (IsUdpcRecvStart) |
| | | { |
| | | thrRecv.Abort(); // 必须先关闭这个线程,否则会异常 |
| | | thrRecv.Dispose(); // 必须先关闭这个线程,否则会异常 |
| | | udpcRecv.Close(); |
| | | IsUdpcRecvStart = false; |
| | | Console.WriteLine("UDP监听器已成功关闭"); |
| | |
| | | /// 接收数据 |
| | | /// </summary> |
| | | /// <param name="obj"></param> |
| | | private static void ReceiveMessage(object obj) |
| | | private static void ReceiveMessage() |
| | | { |
| | | while (IsUdpcRecvStart) |
| | | { |
| | | try |
| | | { |
| | | byte[] bytRecv = udpcRecv.Receive(ref localIpep); |
| | | foreach (var a in bytRecv) |
| | | { |
| | | Console.Write(a); |
| | | Console.Write("-"); |
| | | } |
| | | string message = Encoding.UTF8.GetString(bytRecv, 0, bytRecv.Length); |
| | | Console.WriteLine(string.Format("{0}[{1}]", localIpep, message)); |
| | | |