业务方法
public override async Task<List<(IPEndPoint endPoint, byte[] data)>> SendAsync(IPEndPoint server, byte[] data2, int getResponseCount = 1)
{
//随机使用端口,支持并发
using (UdpClient udpClient = new UdpClient(LocalIPEndPoint)) //广播包在有虚拟机的时候必须指定有效网卡
{ //多网卡容易丢包
udpClient.Client.SendTimeout = SendTimeout;
udpClient.Client.ReceiveTimeout = ReceiveTimeout;
byte[] data = IsEncrypt ? Encrypt(data2) : data2;
try
{
int sendLength = await udpClient.SendAsync(data, data.Length, server);
//int sendLength = 0;
//udpClient.SendAsync(data, data.Length, server).Wait(SendTimeout); //同步方法
Log?.Invoke($"send:{server.ToString()},Len:{sendLength}/{data.Length},Data:{new Q.Mina.IoBuffer(data).getHexDump()}");
udpClient.Close();
return result;
}
catch (Exception ex)
{
return null;
}
}
}
@@#
对上述方法调用,可以使用三种方式
异步,业务方法正常执行,超时处理正常,推荐使用此方法
var result = await new Q.Sockets.UDPHelper2() { LocalIPEndPoint = localIP, ReceiveTimeout = 1000 }.SendAsync(ip, data, 1000);
@@#
同步,超时未生效,一直处于等待状态,除非方法内使用udpClient.SendAsync(data, data.Length, server).Wait(SendTimeout); //同步方法
new Q.Sockets.UDPHelper2() { LocalIPEndPoint = localIP, ReceiveTimeout=1000 }.SendAsync(ip, data, 1000).Result
@@#
等待指定时间,强行在外部指定超时,打断了业务方法的执行时间(如接收大量数据)
var x = new Q.Sockets.UDPHelper2() { LocalIPEndPoint = localIP, ReceiveTimeout = 1000 }.SendAsync(ip, data, 1000);
x.Wait(3000);
if (x.IsCompleted)
{
show(x.Result);
}
@@#