views:

652

answers:

3

Hello All.

I am wondering whether I can set a timeout value for UdpClient receive method.

I want to use block mode, but because sometimes udp will lost packet, my program udpClient.receive will hang there forever.

any good ideas how I can manage that?

A: 

There is a ReceiveTimeout property you can use.

Filip Ekberg
+1  A: 

What Filip is referring to is nested within the socket that UdpClient contains (UdpClient.Client.ReceiveTimeout).

You can also use the async methods to do this, but manually block execution:

var timeToWait = TimeSpan.FromSeconds(10);

var udpClient = new UdpClient( portNumber );
var asyncResult = udpClient.BeginReceive( null, null );
asyncResult.AsyncWaitHandle.WaitOne( timeToWait );
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
}
Brad
Thanks for the reply.
Jack
A: 

asyncResult.AsyncWaitHandle.WaitOne( timeToWait );

Hello, this is not working to me.. Can you explain me why? No overload for method 'WaitOne' takes '1' arguments

Thank you!!!

Giannis