using System.ComponentModel; using System.Net; using System.Net.Sockets; namespace JiLinApp.Docking.FenceAlarm; public class Udp { private BackgroundWorker back = null; /// /// 用于UDP发送的网络服务类 /// private UdpClient udpcSend = null; /// /// 用于UDP接收的网络服务类 /// private UdpClient udpcRecv; public delegate void UDPReceive(string IP, byte[] str);// public event UDPReceive myUDPReceive;// public Udp(string ip, int port) { IPEndPoint localIpep = new IPEndPoint( IPAddress.Parse(ip), port); // 本机IP和监听端口号 udpcRecv = new UdpClient(localIpep); udpcSend = new UdpClient(); back = new BackgroundWorker(); back.WorkerSupportsCancellation = true; back.DoWork += back_DoWork; back.RunWorkerAsync(); } ~Udp() { Stop(); } public void Stop() { if (back != null) { back.CancelAsync(); back = null; } if (udpcRecv != null) { udpcRecv.Close(); udpcRecv = null; } if (udpcSend != null) { udpcSend.Close(); udpcSend = null; } } public bool SendMessage(byte[] sendbytes, string IP, int port) { IPEndPoint remoteIpep = new IPEndPoint( IPAddress.Parse(IP), port); // 发送到的IP地址和端口号 int result = udpcSend.Send(sendbytes, sendbytes.Length, remoteIpep); return result >= sendbytes.Length; } private void back_DoWork(object sender, DoWorkEventArgs e) { IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0); while (!back.CancellationPending) { try { byte[] bytRecv = udpcRecv.Receive(ref remoteIpep); myUDPReceive(remoteIpep.Address.ToString(), bytRecv); } catch { } } } }