using JiLinApp.Docking.VibrateAlarm; using System.ComponentModel; using System.Net; using System.Net.Sockets; namespace JiLinApp.Docking.FenceAlarm; public class UdpServer { #region Fields /// /// 用于UDP接收的网络服务类 /// private UdpClient RecvUdp { get; } /// /// 用于UDP发送的网络服务类 /// private UdpClient SendUdp { get; } private BackgroundWorker Worker { get; } #region Properties public string RecvIp { get; private set; } public int RecvPort { get; private set; } #endregion Properties #endregion Fields #region Ctors public UdpServer(int port) : this("0.0.0.0", port) { } public UdpServer(string ip, int port) { RecvIp = ip; RecvPort = port; RecvUdp = new(new IPEndPoint(IPAddress.Parse(ip), port)); SendUdp = new(new IPEndPoint(IPAddress.Any, 0)); Worker = new() { WorkerSupportsCancellation = true }; Worker.DoWork += Back_DoWork; } ~UdpServer() { Stop(); } #endregion Ctors #region Server public void Start() { if (IsRunning()) return; Worker.RunWorkerAsync(); } public void Stop() { if (!IsRunning()) return; Worker.CancelAsync(); RecvUdp.Close(); SendUdp.Close(); } public bool IsRunning() { return Worker != null && Worker.IsBusy; } #endregion Server #region Events public event EventHandler>? DatagramReceived; private void RaiseDatagramReceived(IPEndPoint ipep, byte[] datagram) { DatagramReceived?.Invoke(this, new UdpDatagramReceivedEventArgs(ipep, datagram)); } #endregion Events #region Receive private void Back_DoWork(object? sender, DoWorkEventArgs e) { IPEndPoint remoteIpep = new(IPAddress.Any, 0); while (Worker != null && !Worker.CancellationPending) { try { byte[] bytRecv = RecvUdp.Receive(ref remoteIpep); RaiseDatagramReceived(remoteIpep, bytRecv); } catch { } } } #endregion Receive #region Send public bool SendMessage(string ip, int port, byte[] msg) { IPEndPoint ipep = new(IPAddress.Parse(ip), port); int result = SendUdp.Send(msg, msg.Length, ipep); bool flag = result == msg.Length; Console.WriteLine("Send to {0}:{1} => {2}, {3}, {4}", ip, port, DataMessage.ToHexString(msg), DataMessage.ToHexString(AlarmEncode.DecodeMessage(msg)), flag); return flag; } public bool SendMessage(IPEndPoint ipep, byte[] msg) { string ip = ipep.Address.ToString(); int port = ipep.Port; int result = SendUdp.Send(msg, msg.Length, ipep); bool flag = result == msg.Length; Console.WriteLine("Send to {0}:{1} => {2}, {3}", ip, port, DataMessage.ToHexString(AlarmEncode.DecodeMessage(msg)), flag); return flag; } #endregion Send }