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.
85 lines
2.0 KiB
85 lines
2.0 KiB
using System.ComponentModel;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
|
|
namespace JiLinApp.Docking.FenceAlarm;
|
|
|
|
public class Udp
|
|
{
|
|
private BackgroundWorker back = null;
|
|
|
|
/// <summary>
|
|
/// 用于UDP发送的网络服务类
|
|
/// </summary>
|
|
private UdpClient udpcSend = null;
|
|
|
|
/// <summary>
|
|
/// 用于UDP接收的网络服务类
|
|
/// </summary>
|
|
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
|
|
{
|
|
}
|
|
}
|
|
}
|
|
}
|