Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting socket send/receive timeout to less than 500ms in .NET

Tags:

c#

.net

sockets

According to MSDN documentation it is not possible to set Socket.SendTimeout to a value less than 500ms: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.sendtimeout Same rule is valid for Socket.ReceiveTimeout (even it is not mentioned in MSDN documentation, this is true, as both cases were tested practically).

Are there any other ways to timeout a socket receive operation if it, for example, takes longer than 10ms to complete?

like image 733
donatasm Avatar asked May 28 '12 14:05

donatasm


1 Answers

The simple answer is "you don't".

Send() and Receive() calls block the flow of the program until data was sent, received or an error occurred.

If you want to have more control over your calls, there are several mechanisms available. The simplest is to use Poll().

Socket s;
// ...
// Poll the socket for reception with a 10 ms timeout.
if (s.Poll(10000, SelectMode.SelectRead))
{
    s.Receive(); // This call will not block
}
else
{
    // Timed out
}

You can also use Select(), BeginReceive() or ReceiveAsync() for other types of behaviors.

I recommend you read Stevens' UNIX Network Programming chapters 6 and 16 for more in-depth information on non-blocking socket usage. Even though the book has UNIX in its name, the overall sockets architecture is essentially the same in UNIX and Windows (and .net)

like image 166
user1003819 Avatar answered Nov 10 '22 01:11

user1003819