How to check if a socket is connected/disconnected in C#?

前端 未结 11 1230
礼貌的吻别
礼貌的吻别 2020-11-28 18:50

How can you check if a network socket (System.Net.Sockets.Socket) is still connected if the other host doesn\'t send you a packet when it disconnects (e.g. because it discon

11条回答
  •  囚心锁ツ
    2020-11-28 19:25

    As Alexander Logger pointed out in zendars answer, you have to send something to be completely sure. In case your connected partner does not read on this socket at all, you can use the following code.

    bool SocketConnected(Socket s)
    {
      // Exit if socket is null
      if (s == null)
        return false;
      bool part1 = s.Poll(1000, SelectMode.SelectRead);
      bool part2 = (s.Available == 0);
      if (part1 && part2)
        return false;
      else
      {
        try
        {
          int sentBytesCount = s.Send(new byte[1], 1, 0);
          return sentBytesCount == 1;
        }
        catch
        {
          return false;
        }
      }
    }
    

    But even then it might take a few seconds until a broken network cable or something similar is detected.

提交回复
热议问题