Socket receivetimeout

I specified ReceiveTimout as 40 ms. But it takes more than 500 ms to receive a timeout. I use a stopwatch to calculate the time.

The code is shown below.

 Socket TCPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); TCPSocket.ReceiveTimeout = 40; try { TCPSocket.Receive(Buffer); } catch(SocketException e) { } 
+6
source share
3 answers

You can synchronously interrogate any timeout in the socket. If Poll() returns true , you can be sure that you can make a Receive() call that will not block.

 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 } 

I recommend that you read Chapters 6 and 16 of Stevens' UNIX Network Programming for more information on non-blocking socket usage. Although the book has UNIX in its title, the general socket architecture is essentially the same on UNIX and Windows (and .net)

+7
source

You cannot use timeout values ​​that are less than 500 ms. See SendTimeout here: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.sendtimeout

Although MSDN does not specify the same requirement for ReceiveTimeout , my experience shows that this limitation still exists.

You can also read several SO posts about this:

+2
source

I found this:

 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IAsyncResult result = socket.BeginConnect( sIP, iPort, null, null ); bool success = result.AsyncWaitHandle.WaitOne( 40, true ); if ( !success ) { socket.Close(); throw new ApplicationException("Failed to connect server."); } 
0
source

Source: https://habr.com/ru/post/908699/


All Articles