1.简单的使用UDP对接示例:
/// <summary>
/// 定时器,每秒定时获取是否有udp数据
/// </summary>
public DispatcherTimer Timer1 = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 1) };
public UdpClient SocketUDP { get; set; }
//初始化事件,注意异常处理及SocketUDP释放
{
//未连接状态时创建连接
SocketUDP = new UdpClient(new IPEndPoint(IPAddress.Parse(IP), int.Parse(Port)));
//定时获取查询是否有数据
Timer1.Tick += Timer1_Tick;
}
private void Timer1_Tick(object sender, EventArgs e)
{
IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse(IP), int.Parse(Port));
Task.Run(async () =>
{
Timer1.Stop();
try
{
byte[] bytRecv = SocketUDP.Receive(ref remoteIpep);
#region 应答UDP
var sendData = Encoding.UTF8.GetBytes("OK");
SocketUDP.Send(sendData, sendData.Length, remoteIpep);
#endregion
string message = Encoding.Default.GetString(bytRecv, 0, bytRecv.Length);
}
catch (Exception ex)
{
LogHelper.WriteLog(ex.ToString(), "C:\\Temp\\logs/FCT/");
}
finally
{
Timer1.Start();
}
});
}
在这个例子中,有一个接收方。接收方监听指定的IP和端口,接收到消息后并回应"OK"。
需要注意的是,需要确保发送方和接收方的IP和端口是正确配置的,并且在同一网络中。
2.模拟发送,测试代码逻辑
注意本地主机(调试助手的ip端口)和远程主机(代码里绑定的ip端口)填写正确