Monday, April 14, 2008

Change socket send and receive timeout

Sometimes synchronous Socket I/O methods like Send or Receive take too long to complete or produce an error (exception). This default behavior can be changed using socket options. Namely, SocketOptionName.SendTimeout and SocketOptionName.ReceiveTimeout.

Here's code sample how to get/set these socket options:


//get socket receive timeout
int timeout = (int)socket.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout);

//set socket receive timeout
int timeout = 0;
socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, timeout);

Nearly the same code is for SendTimeout socket option

//get socket send timeout
int timeout = (int)socket.GetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeout);

//set socket send send timeout
int timeout = 0;
socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeout, timeout);


When you do not use synchronous I/O but instead use BeginXXX/EndXXX or non-blocking sockets then you can let the system handle long lasting I/O. You no longer need to handle timeouts, since your code is not waiting for the I/O to complete.

If you still want to wait for asynchronous operation to complete you can use AsyncWaitHandle property of the IAsyncResult interface.

IAsyncResult result = socket.BeginReceive(/*parameters come here*/);
//here we can wait for 5 minutes for completion of receive operation
result.AsyncWaitHandle.WaitOne(5*60*1000, false);

No comments:

Post a Comment