using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace WOLAwaken.Helper { public class ReceiveUDPPack { /// /// 用于UDP发送的网络服务类 /// static UdpClient udpcRecv = null; static IPEndPoint localIpep = null; /// /// 开关:在监听UDP报文阶段为true,否则为false /// static bool IsUdpcRecvStart = false; /// /// 线程:不断监听UDP报文 /// 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(receiveIp), receivePort); // 本机IP和监听端口号 udpcRecv = new UdpClient(localIpep); thrRecv = new Task(() => { ReceiveMessage(); }); thrRecv.Start(); IsUdpcRecvStart = true; Console.WriteLine("UDP监听器已成功启动"); } } public static void StopReceive() { if (IsUdpcRecvStart) { thrRecv.Dispose(); // 必须先关闭这个线程,否则会异常 udpcRecv.Close(); IsUdpcRecvStart = false; Console.WriteLine("UDP监听器已成功关闭"); } } /// /// 接收数据 /// /// 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)); } catch (Exception ex) { Console.WriteLine(ex.Message); break; } } } } }