Instantly detect client disconnection from server socket

后端 未结 14 1430
北恋
北恋 2020-11-22 09:27

How can I detect that a client has disconnected from my server?

I have the following code in my AcceptCallBack method

static Socket hand         


        
14条回答
  •  感情败类
    2020-11-22 09:40

    Since there are no events available to signal when the socket is disconnected, you will have to poll it at a frequency that is acceptable to you.

    Using this extension method, you can have a reliable method to detect if a socket is disconnected.

    static class SocketExtensions
    {
      public static bool IsConnected(this Socket socket)
      {
        try
        {
          return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
        }
        catch (SocketException) { return false; }
      }
    }
    

提交回复
热议问题