我想知道是否可以为 UdpClient 接收方法设置超时值。
我想使用块模式,但因为有时 udp 会丢失数据包,我的程序 udpClient.receive 将永远挂在那里。
有什么好主意吗?
您可以在 的中使用aSendTimeout
和 a属性。ReceiveTimeout
Socket
UdpClient
以下是 5 秒超时的示例:
var udpClient = new UdpClient();
udpClient.Client.SendTimeout = 5000;
udpClient.Client.ReceiveTimeout = 5000;
...
Filip 所指的是嵌套在UdpClient
包含 ( UdpClient.Client.ReceiveTimeout
) 的套接字中。
您也可以使用异步方法来执行此操作,但手动阻止执行:
var timeToWait = TimeSpan.FromSeconds(10);
var udpClient = new UdpClient( portNumber );
var asyncResult = udpClient.BeginReceive( null, null );
asyncResult.AsyncWaitHandle.WaitOne( timeToWait );
if (asyncResult.IsCompleted)
{
try
{
IPEndPoint remoteEP = null;
byte[] receivedData = udpClient.EndReceive( asyncResult, ref remoteEP );
// EndReceive worked and we have received data and remote endpoint
}
catch (Exception ex)
{
// EndReceive failed and we ended up here
}
}
else
{
// The operation wasn't completed before the timeout and we're off the hook
}
UdpClient
实际上,当涉及到超时时,它似乎被打破了。我试图用一个线程编写一个服务器,该线程只包含一个接收数据并将其添加到队列中。多年来,我用 TCP 做过这类事情。期望是循环在接收时阻塞,直到消息来自请求者。但是,尽管将超时设置为无穷大:
_server.Client.ReceiveTimeout = 0; //block waiting for connections
_server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
大约 3 分钟后套接字超时。
我发现的唯一解决方法是捕获超时异常并继续循环。这隐藏了 Microsoft 错误,但未能回答为什么会发生这种情况的基本问题。
你可以这样做:
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
您可以使用 ReceiveTimeout 属性。