How can I tell if the connection has been broken in my sockets based client?

前端 未结 6 1072
小鲜肉
小鲜肉 2020-12-11 18:11

If my client\'s connection is broken on the other end( kill -9 server). It takes several minutes for the client to determine that something is wrong. Sock

6条回答
  •  旧时难觅i
    2020-12-11 18:38

    Try checking the Available property, it should throw a SocketException when the connection has been closed.

    Source

    Edit, here is how you would use it:

    while(socket.Connected)
    {
      try
      {
        while (socket.Available == 0)
          System.Threading.Thread.Sleep(100); // Zzzz
      }
      catch (SocketException)
      {
        // connection closed
        // do something
      }
    
      /* Do some processing */
    }
    

    You could also try using the Poll method.

    From Source:

    Alternatively, you can also utilize the Poll() Socket method with the SelectRead SelectMode parameter. This method will return a true value if data is available or if the connection has been closed by the remote host. You will then need to differentiate between which of these situations has occurred (by reading the socket buffer, and seeing if it returns a zero value).

提交回复
热议问题