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.
 

84 lines
1.9 KiB

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Leit.FrameWork
{
public class UdpHelper
{
public UdpHelper()
{
Udpclient = new UdpClient();
}
public UdpHelper(int port)
{
Udpclient = new UdpClient(port);
}
public event Action<MsgStruct> ReceiveUdpMsg;
/// <summary>
/// Udp客户端
/// </summary>
public UdpClient Udpclient { get; set; }
public bool StopReceive { get; set; }
public void SendMsg(int port, MsgStruct msg)
{
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, port);
byte[] sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(msg)); // 将消息编码成字符串数组
Udpclient.Send(sendBytes, sendBytes.Length, iep); // 发送数据报
}
/// <summary>
/// 接收消息
/// </summary>
public void ReciveMsg()
{
Task.Run(() => {
IPEndPoint remoteIpEndPoint =null; // 远程端点,即发送消息方的端点
while (!StopReceive)
{
byte[] receiveBytes = Udpclient.Receive(ref remoteIpEndPoint); // 接收消息,得到数据报
string returnData = Encoding.UTF8.GetString(receiveBytes); // 解析字节数组,得到原消息
try
{
ReceiveUdpMsg?.Invoke((MsgStruct)JsonConvert.DeserializeObject(returnData, typeof(MsgStruct)));
}
catch
{
}
}
});
}
}
}