怎样让socket的server得知client已经断开了连接?
在正常情况下(关闭client程序,关闭client的进程)在ReceiveCallback中都可以捕捉到client连接断开了,但是在拔掉client机器上的网线,server却不能捕捉到,当然client自己可以捕捉到,server不知道,在server保存的client的列表里,找到那个client判断Connected属性也是true.只有再发送写东西,然后才会抛出这个client断开。
请问有没有不通过对client轮询发送信息来判断这个tcp连接已经失效呢?

解决方案 »

  1.   

    参考:http://www.codeguru.com/article.php/c8781
    How to Find when a Particular Client is Disconnected:When a client is disconnected, there will be a final call to the OnDataReceived() function. If nothing in particular is done, this call will throw a SocketException. What you can do here is to look inside this exception and see whether this was triggered by the "disconnection" of a client. For this, you will look at the error code inside the exception object and see whether it corresponds to 10054. If so, you will do the required action corresponding to the client disconnection. Here again, the SocketPacket object will give you the index number of the client that was disconnected.catch(SocketException se)
    {
       if(se.ErrorCode == 10054)    // Error code for Connection reset
                                    // by peer
       {
          string msg = "Client " + socketData.m_clientNumber +
                       " Disconnected" + "\n";
          richTextBoxReceivedMsg.AppendText(msg);      // Remove the reference to the worker socket of the closed
          // client so that this object will get garbage collected
          m_workerSocketList[socketData.m_clientNumber - 1] = null;
          UpdateClientList();
       }
       else
       {
          MessageBox.Show (se.Message );
       }
    }
      

  2.   

    我在实际开发中使用的方法如下:
    try
    {
    int len = clientSocket.Receive(new byte[1], SocketFlags.Peek);
    if (len > 0)
    {
               //the client socket is not connected
      //...
    }
    }
    catch (SocketException se)
    {
      
        if (se.ErrorCode == 10054) // Error code for Connection reset by peer
        {
    //...
         }
    }
      

  3.   

    to:jiezhi(风满袖) 
    在server不对client发包的情况下,server是捕捉不到错误信息的.也就是说没有抛出异常信息.
      

  4.   

    为何把网线,硬重起,直接断电,直接按电源关机这些情况,server在不发包的情况下,都不能抛异常呢????
    ---------------------------------------
    看看tcp/ip协议吧,没有什么好奇怪的。
    我第二个回复的代码你看了吗?
    int len = clientSocket.Receive(new byte[1], SocketFlags.Peek);
    if (len > 0)
    {
               //the client socket is not connected
      //...
    }//这样可以检测的。我用了一个线程来检测每个socket 连接的可用性。
      

  5.   

    我的方式是:socket.SendTo(new byte[1],socket.RemoteEndPoint);
    让server发包,当client连接不存在的时候会在Receive时候抛异常,来判断。
      

  6.   

    你的做法不合适。
    你server发送(send)的时候不判断,receive判断什么啊?
    发送的时候就要判断client的socket是否可用。数据通过网络传输,什么都有可能发生。