[英]Can I set the timeout for UdpClient in C#?
我想知道是否可以为 UdpClient 接收方法设置超时值。
我想使用块模式,但因为有时 udp 会丢失数据包,我的程序 udpClient.receive 将永远挂在那里。
有什么好主意,我该如何管理?
您可以在UdpClient
的Socket
中使用一个SendTimeout
和ReceiveTimeout
属性。
这是5秒超时的示例:
var udpClient = new UdpClient();
udpClient.Client.SendTimeout = 5000;
udpClient.Client.ReceiveTimeout = 5000;
...
Filip所指的是嵌套在UdpClient
包含的套接字( UdpClient.Client.ReceiveTimeout
)中。
您也可以使用async方法来执行此操作,但要手动阻止执行:
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的错误,但无法回答发生这种情况的根本问题。
您可以使用一个ReceiveTimeout属性。
您可以这样:
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
由于我没有 50 的声誉,我不能直接发表评论。 不过,我想指出,最好的帖子及其代码并不是解决方案。 因为BeginReceive总是需要一个EndReceive,否则在数百次请求后,BeginReceive队列溢出,这不是解决方案。 但是,如果对块使用 EndReceive(不幸的是需要),则调用块,这意味着最后没有超时。 在这方面,不幸的是 Brad Nebholz 的代码不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.