Socket.EndRead 0 bytes means disconnected?

2019-03-30 06:38发布

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?  
  }
}

2条回答
爷的心禁止访问
2楼-- · 2019-03-30 06:59

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.

查看更多
成全新的幸福
3楼-- · 2019-03-30 07:02

0 read length should mean gracefull shutdown. Disconnect throws error (10054, 10053 or 10051).

In practice though I did notice reads complete with 0 length even though the connection was alive, and the only way to handle is to check the socket status on 0 length reads. The situation was as follows: post multiple buffers on a socket for receive. The thread that posted then is trimmed by the pool. The OS notices that the thread that made the requests is gone and it notifies the posted operations with error 995 ERROR_OPERATION_ABORTED, as documented. However what I've found is that when multiple operations are posted (ie. multiple Reads) only the first is notified with error 995, the subsequent are notified with success and 0 length.

查看更多
登录 后发表回答