Can Socket.Receive() return 0 if the connection is still open?
I am writing a C# .NET server application that sends an开发者_如何学Pythond 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)
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.
精彩评论