You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.4 KiB

2 years ago
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
namespace JiLinApp.Docking.FenceAlarm;
public class Udp
{
#region Fields
private BackgroundWorker BackWorker { get; }
2 years ago
/// <summary>
/// 用于UDP接收的网络服务类
2 years ago
/// </summary>
private UdpClient RecvUdp { get; }
2 years ago
/// <summary>
/// 用于UDP发送的网络服务类
2 years ago
/// </summary>
private UdpClient SendUdp { get; }
#endregion Fields
2 years ago
#region Ctors
2 years ago
public Udp(int port) : this("0.0.0.0", port)
{
}
2 years ago
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();
2 years ago
}
~Udp()
{
Stop();
}
#endregion Ctors
#region Server
2 years ago
public void Stop()
{
BackWorker?.CancelAsync();
RecvUdp?.Close();
SendUdp?.Close();
2 years ago
}
#endregion Server
#region Receive
public delegate void UDPReceive(IPEndPoint ipep, byte[] str);
public event UDPReceive DatagramReceived;
private void RaiseDatagramReceived(IPEndPoint ipep, byte[] datagram)
2 years ago
{
DatagramReceived?.Invoke(ipep, datagram);
2 years ago
}
#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)
2 years ago
{
IPEndPoint remoteIpep = new(IPAddress.Any, 0);
while (BackWorker != null && !BackWorker.CancellationPending)
2 years ago
{
try
{
byte[] bytRecv = RecvUdp.Receive(ref remoteIpep);
DatagramReceived(remoteIpep, bytRecv);
2 years ago
}
catch
{
throw;
2 years ago
}
}
}
}