I am writing a C# .NET server application that sends and receives data over Sockets, and I am having some issues if the client application crashes without closing the socket the right way.
I have set the 'receive timeout' to a given value, and I expected the Socket.Receive() to throw an exception after that amount of time. But instead the method just returns 0.
So my question is: Is it possible that the socket is still open if the Socket.Receive()
returns 0? Or can I safely assume that it is down?
(Might be a bit tricky to understand. If so, please let me know in the comments)
The Receive method reads data into the buffer parameter and returns the number of bytes successfully read. You can call Receive from both connection-oriented and connectionless sockets. This overload only requires you to provide a receive buffer, the number of bytes you want to receive, and the necessary SocketFlags.
If the socket is in non-blocking mode, recv() will return -1 immediately if there's nothing available, and errno will be set to EWOULDBLOCK .
Nope. It's down if you receive 0.
From MSDN:
If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.
http://msdn.microsoft.com/en-us/library/8s4y8aff.aspx
Your question is a little confused. The Socket is open until you close it. The connection is open until either end closes it. The read side of a connection can be closed by the sender shutting it down for output. So when reading a connection you will receive zero if the peer has either closed his socket or shut it down for output. At that point, your socket is still open, although you should now close it.
It will also return zero if the local application has shutdown the socket for input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With