|
|
|
using System.ComponentModel;
|
|
|
|
using System.Net;
|
|
|
|
using System.Net.Sockets;
|
|
|
|
|
|
|
|
namespace JiLinApp.Docking.FenceAlarm;
|
|
|
|
|
|
|
|
public class Udp
|
|
|
|
{
|
|
|
|
#region Fields
|
|
|
|
|
|
|
|
private BackgroundWorker BackWorker { get; }
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 用于UDP接收的网络服务类
|
|
|
|
/// </summary>
|
|
|
|
private UdpClient RecvUdp { get; }
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 用于UDP发送的网络服务类
|
|
|
|
/// </summary>
|
|
|
|
private UdpClient SendUdp { get; }
|
|
|
|
|
|
|
|
#endregion Fields
|
|
|
|
|
|
|
|
#region Ctors
|
|
|
|
|
|
|
|
public Udp(int port) : this("0.0.0.0", port)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
public Udp(string ip, int port)
|
|
|
|
{
|
|
|
|
RecvUdp = new(new IPEndPoint(IPAddress.Parse(ip), port));
|
|
|
|
SendUdp = new(new IPEndPoint(IPAddress.Any, 0));
|
|
|
|
BackWorker = new BackgroundWorker
|
|
|
|
{
|
|
|
|
WorkerSupportsCancellation = true
|
|
|
|
};
|
|
|
|
BackWorker.DoWork += Back_DoWork;
|
|
|
|
BackWorker.RunWorkerAsync();
|
|
|
|
}
|
|
|
|
|
|
|
|
~Udp()
|
|
|
|
{
|
|
|
|
Stop();
|
|
|
|
}
|
|
|
|
|
|
|
|
#endregion Ctors
|
|
|
|
|
|
|
|
#region Server
|
|
|
|
|
|
|
|
public void Stop()
|
|
|
|
{
|
|
|
|
BackWorker?.CancelAsync();
|
|
|
|
RecvUdp?.Close();
|
|
|
|
SendUdp?.Close();
|
|
|
|
}
|
|
|
|
|
|
|
|
#endregion Server
|
|
|
|
|
|
|
|
#region Receive
|
|
|
|
|
|
|
|
public delegate void UDPReceive(IPEndPoint ipep, byte[] str);
|
|
|
|
|
|
|
|
public event UDPReceive DatagramReceived;
|
|
|
|
|
|
|
|
private void RaiseDatagramReceived(IPEndPoint ipep, byte[] datagram)
|
|
|
|
{
|
|
|
|
DatagramReceived?.Invoke(ipep, datagram);
|
|
|
|
}
|
|
|
|
|
|
|
|
#endregion Receive
|
|
|
|
|
|
|
|
#region Send
|
|
|
|
|
|
|
|
public bool SendMessage(string ip, int port, byte[] byteMsg)
|
|
|
|
{
|
|
|
|
IPEndPoint ipep = new(IPAddress.Parse(ip), port); // 发送到的IP地址和端口号
|
|
|
|
int result = SendUdp.Send(byteMsg, byteMsg.Length, ipep);
|
|
|
|
bool flag = result >= byteMsg.Length;
|
|
|
|
Console.WriteLine("Send ok: {0}", flag);
|
|
|
|
return flag;
|
|
|
|
}
|
|
|
|
|
|
|
|
public bool SendMessage(IPEndPoint ipep, byte[] byteMsg)
|
|
|
|
{
|
|
|
|
int result = SendUdp.Send(byteMsg, byteMsg.Length, ipep);
|
|
|
|
return result >= byteMsg.Length;
|
|
|
|
}
|
|
|
|
|
|
|
|
#endregion Send
|
|
|
|
|
|
|
|
private void Back_DoWork(object? sender, DoWorkEventArgs e)
|
|
|
|
{
|
|
|
|
IPEndPoint remoteIpep = new(IPAddress.Any, 0);
|
|
|
|
while (BackWorker != null && !BackWorker.CancellationPending)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
byte[] bytRecv = RecvUdp.Receive(ref remoteIpep);
|
|
|
|
DatagramReceived(remoteIpep, bytRecv);
|
|
|
|
}
|
|
|
|
catch
|
|
|
|
{
|
|
|
|
throw;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|