40

我想知道是否可以为 UdpClient 接收方法设置超时值。

我想使用块模式,但因为有时 udp 会丢失数据包,我的程序 udpClient.receive 将永远挂在那里。

有什么好主意吗?

4

5 回答 5

66

您可以在 的中使用aSendTimeout和 a属性。ReceiveTimeoutSocketUdpClient

以下是 5 秒超时的示例:

var udpClient = new UdpClient();

udpClient.Client.SendTimeout = 5000;
udpClient.Client.ReceiveTimeout = 5000;

...
于 2011-04-16T04:42:02.597 回答
35

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
}
于 2010-02-17T14:42:50.717 回答
4

UdpClient实际上,当涉及到超时时,它似乎被打破了。我试图用一个线程编写一个服务器,该线程只包含一个接收数据并将其添加到队列中。多年来,我用 TCP 做过这类事情。期望是循环在接收时阻塞,直到消息来自请求者。但是,尽管将超时设置为无穷大:

_server.Client.ReceiveTimeout = 0; //block waiting for connections
_server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);

大约 3 分钟后套接字超时。

我发现的唯一解决方法是捕获超时异常并继续循环。这隐藏了 Microsoft 错误,但未能回答为什么会发生这种情况的基本问题。

于 2012-06-01T17:48:49.993 回答
4

你可以这样做:

udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
于 2017-08-29T20:37:19.563 回答
3

您可以使用 ReceiveTimeout 属性。

于 2010-02-17T14:38:50.270 回答