Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm making the following BeginReceive call on a socket:

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

in my classes 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 issue I'm having is that EndReceive is returning zero, but m_socket.Connected is returning true, so I call BeginReceive again. This occurs in a tight loop which doesn't ever stop. It's not clear from the documentation when EndReceive returns a zero. I assumed it only happens when the socket is closed, but this does no appear to be true.

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

like image 655
bpeikes Avatar asked Nov 04 '14 17:11

bpeikes


1 Answers

Socket.EndReceive() returns 0 in one specific case: the remote host has begun or acknowledged the graceful closure sequence (e.g. for a .NET Socket-based program, calling Socket.Shutdown() with either SocketShutdown.Send or SocketShutdown.Both).

However note that technically, until the socket is finally closed, it is "connected".

You should not use the Connected property to determine whether to issue another read from the socket. Instead, since a return value of 0 is specifically reserved to indicate that no more data will be sent, you should simply check the return value of EndReceive() and call BeginReceive() again if the value is a positive number (i.e. not zero).

like image 79
Peter Duniho Avatar answered Oct 30 '22 00:10

Peter Duniho