Jac*_*ack 35 c# timeout udpclient
我想知道我是否可以为UdpClient接收方法设置超时值.
我想使用块模式,但因为有时udp会丢失数据包,我的程序udpClient.receive将永远挂在那里.
我有什么好主意可以管理它?
小智 59
有一个SendTimeout和一个ReceiveTimeout属性,你可以使用Socket的UdpClient.
以下是5秒超时的示例:
var udpClient = new UdpClient();
udpClient.Client.SendTimeout = 5000;
udpClient.Client.ReceiveTimeout = 5000;
...
Run Code Online (Sandbox Code Playgroud)
Bra*_*olz 27
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41718 次 |
| 最近记录: |