Should EndReceive ever return zero if the connector is still connected?

I am making the following call to BeginReceive on a socket:

m_socket.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.Partial, this.ReceiveCallback, null);

      

in my classes the ReceiveCallback

function i call

try {
    int bytesReadFromSocket = m_socket.EndReceive(ar);
    if(bytesReadFromSocket > 0) {
         // Do some processing
    }
}
finally {
   if(m_socket.Connected) m_socket.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.Partial, this.ReceiveCallback, null);
}

      

The problem I am running into is that EndReceive returns zero, but m_socket.Connected returns true, so I call BeginReceive again. It happens in a closed loop that never stops. It is not clear from the documentation when EndReceive returns zero. I assumed this only happens when the socket is closed, but that doesn't seem to be true.

So the question remains, under what conditions can EndReceive return zero?

+3


source to share


1 answer


Socket.EndReceive()

returns 0 in one specific case: the remote host has started or acknowledged a graceful closing sequence (for example, for a .NET based program Socket

, calling Socket.Shutdown()

with SocketShutdown.Send

or SocketShutdown.Both

).

Note, however, that technically, until a socket is finally closed, it is "connected".



The property cannot be used Connected

to determine whether to issue another read from the socket. Instead, since the return value 0 is specifically reserved to indicate that no more data will be sent, you should simply check the return value EndReceive()

and call again BeginReceive()

if the value is a positive number (that is, not zero).

+3


source







All Articles