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

前端 未结 11 1209
礼貌的吻别
礼貌的吻别 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条回答
  •  Happy的楠姐
    2020-11-28 19:10

    Following the advice from NibblyPig and zendar, I came up with the code below, which works on every test I made. I ended up needing both the ping, and the poll. The ping will let me know if the cable has been disconnected, or the physical layer otherwise disrupted (router powered off, etc). But sometimes after reconnect I get a RST, the ping is ok, but the tcp state is not.

    #region CHECKS THE SOCKET'S HEALTH
        if (_tcpClient.Client.Connected)
        {
                //Do a ping test to see if the server is reachable
                try
                {
                    Ping pingTest = new Ping()
                    PingReply reply = pingTest.Send(ServeripAddress);
                    if (reply.Status != IPStatus.Success) ConnectionState = false;
                } catch (PingException) { ConnectionState = false; }
    
                //See if the tcp state is ok
                if (_tcpClient.Client.Poll(5000, SelectMode.SelectRead) && (_tcpClient.Client.Available == 0))
                {
                    ConnectionState = false;
                }
            }
        }
        else { ConnectionState = false; }
    #endregion
    

提交回复
热议问题