Socket.EndRead 0字节意味着断开连接? [英] Socket.EndRead 0 bytes means disconnected?

查看:325
本文介绍了Socket.EndRead 0字节意味着断开连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在c#的异步套接字中,在EndRead调用中接收0字节是否意味着服务器实际上断开了我们的连接?

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.

此代码正确吗?还是endResult< = 0真的与连接状态无关吗?

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

推荐答案

0读取长度应表示完全关闭.断开连接引发错误(10054、10053或10051).

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

在实践中,尽管我确实注意到即使连接仍处于活动状态,读取也仍以0长度完成,并且处理的唯一方法是检查0长度读取时的套接字状态.情况如下:在套接字上发布多个缓冲区以供接收.然后,发布池将修剪发布的线程.操作系统注意到发出请求的线程已消失,并通知已发布的操作,错误995 ERROR_OPERATION_ABORTED,如所记录.但是我发现的是,当发布多个操作(即多次读取)时,只有 first 被通知错误995,随后的通知被通知成功且长度为0.

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.

这篇关于Socket.EndRead 0字节意味着断开连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆