Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Socket.Receive() return 0 if the connection is still open?

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)

like image 490
Jakob Høgenes Avatar asked Jan 13 '11 21:01

Jakob Høgenes


People also ask

How does Socket receive work?

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.

What does RECV return when there is still data in the buffer but the other side has closed the socket?

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 .


2 Answers

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

like image 149
jgauffin Avatar answered Oct 15 '22 18:10

jgauffin


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.

like image 28
user207421 Avatar answered Oct 15 '22 20:10

user207421