.net使用ReceiveAsync检测断开连接

时间:2009-03-25 19:02:19

标签: .net networking sockets

正如标题所说,我怎么能检测到与所有其他.net网络模式的“ReceiveAsync”的断开连接,如果你复活了0个字节或者抛出了任何异常,你可以看看,但是这似乎不再是真的用这种模式......

我的第一个recive返回0字节,但第二个工作,这就是为什么我困惑....

1 个答案:

答案 0 :(得分:2)

它是一样的:

        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);
            }
        }