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

前端 未结 11 1214
礼貌的吻别
礼貌的吻别 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:13

    I made an extension method based on this MSDN article. This is how you can determine whether a socket is still connected.

    public static bool IsConnected(this Socket client)
    {
        bool blockingState = client.Blocking;
    
        try
        {
            byte[] tmp = new byte[1];
    
            client.Blocking = false;
            client.Send(tmp, 0, 0);
            return true;
        }
        catch (SocketException e)
        {
            // 10035 == WSAEWOULDBLOCK
            if (e.NativeErrorCode.Equals(10035))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        finally
        {
            client.Blocking = blockingState;
        }
    }
    

提交回复
热议问题