我想知道我是否可以为UdpClient接收方法设置超时值。
我想使用阻止模式,但因为有时udp会丢失数据包,我的程序udpClient.receive会永远挂在那里。
任何好的想法我怎么能管理它?
答案 0 :(得分:55)
您可以在SendTimeout
的{{1}}中使用ReceiveTimeout
和Socket
属性。
以下是5秒超时的示例:
UdpClient
答案 1 :(得分:25)
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
}
答案 2 :(得分:3)
实际上,UdpClient
似乎在超时方面被打破了。我试着写一个服务器,其中一个线程只包含一个获取数据的接收并将其添加到队列中。我用TCP做了很多年这样的事情。期望是循环在接收处阻塞,直到消息从请求者进入。但是,尽管将超时设置为无穷大:
_server.Client.ReceiveTimeout = 0; //block waiting for connections
_server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
套接字在约3分钟后超时。
我发现的唯一解决方法是捕获超时异常并继续循环。这隐藏了微软的错误,但没有回答为什么会发生这种情况的根本问题。
答案 3 :(得分:2)
您可以使用ReceiveTimeout属性。
答案 4 :(得分:1)
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);