Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.EndRead 0 bytes means disconnected?

I'm wondering if in my Async Sockets in c#, receiving 0 bytes in the EndRead call means the server has actually disconnected us?

Many Examples I see suggest that this is the case, but I'm receiving disconnects a lot more frequent that I would be expecting.

Is this code correct? Or does endResult <= 0 not really mean anything about the connection state?

private void socket_EndRead(IAsyncResult asyncResult)
{ 
  //Get the socket from the result state
  Socket socket = asyncResult.AsyncState as Socket;

  //End the read
  int endResult = Socket.EndRead(asyncResult);

  if (endResult > 0)
  {
    //Do something with the data here


  }
  else
  {
    //Server closed connection?  
  }
}
like image 712
Redth Avatar asked Mar 01 '23 08:03

Redth


1 Answers

From the docs:

If the remote host shuts down the Socket connection and all available data has been received, the EndRead method completes immediately and returns zero bytes.

So yes, zero bytes indicates a remote close.

like image 78
Mark Rushakoff Avatar answered Mar 08 '23 05:03

Mark Rushakoff