【问题标题】:.net Detect disconnect with ReceiveAsync.net 使用 ReceiveAsync 检测断开连接
【发布时间】:2009-03-25 19:02:18
【问题描述】:

正如标题所说,我如何检测与所有其他 .net 网络模式的“ReceiveAsync”断开连接,如果您收到 0 字节或抛出任何异常,您可以查看,但这似乎不再正确用这种模式...

我的第一个接收返回 0 个字节,但第二个有效,这就是我感到困惑的原因......

【问题讨论】:

  • 您是如何接收数据的?
  • 带socket.ReceiveAsync
  • @Petoj,你能显示一些代码吗?据我所知,回调应该以接收到的字节数为 0 调用。

标签: .net networking sockets


【解决方案1】:

都是一样的:

        void OnReceiveComplete(IAsyncResult iar)
        {
            try
            {
                int count = sock.EndReceive(iar);
                if (count == 0)
                {
                    Console.WriteLine("{0} closed by remote host", ID);
                    sock.Close();
                }
                else
                {
                    int total = Interlocked.Increment(ref totalBytes);
                    Console.WriteLine("{0} received {1} (total: {2})",
                        ID, buff[0], total);
                    StartReceive();
                }
            }
            catch (Exception x)
            {
                Console.WriteLine("{0} error from EndReceive: {1}", ID, x);
            }
        }

【讨论】:

  • 断线时socket不会自动关闭吗?
  • 我使用的是 ReceiveAsync 而不是 BeginReceive 本周晚些时候当我剪掉丑陋的部分时会发布一些代码
  • strager - 我希望不会!这里发生的只是客户端已经关闭了它的发送端(通过调用 Shutdown(Send))并且它不会再发送任何数据。连接现在“半开”,如果需要,您仍然可以发送数据。如果套接字自动关闭,那么这是不可能的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-10
  • 2020-07-07
  • 2013-02-10
相关资源
最近更新 更多