c# TcpClient judges whether the connection status is disconnected

First of all, clarify a problem, TcpClient is the encapsulation of scoket, and TcpClient.Client is the original socket object.

Secondly, you cannot use client.Client.Connected or client.Connected to judge whether it is still connected, because this attribute will only be updated after connecting or actively disconnecting or sending receiving information . It is not a real-time state.

Microsoft said that it is possible to call non-blocking Send() to send a 0-byte message. If the sending is successful, it means that the connection is still connected. If an exception is thrown, the connection has been disconnected. However, it is found in the experiment that it does not work. After the remote end is disconnected, it will be sent. The 0-byte message will still not report an error. It is suspected to be related to the encapsulation of TcpClient. Maybe an empty message will not work directly. So it was changed to send 1 byte, and an error was reported normally after the connection was disconnected.

The method of detecting the connection is as follows, if it is still connected, it will return true, and if it is disconnected, it will return false

 public bool IsSocketConnect(TcpClient client) //判断一个socket是否处于连接状态
    {
    
           
        if (client == null||client.Client == null)
        {
    
    
            return false;
        }
        //先看看状态
        if (client.Client.Connected == false || client.Client.RemoteEndPoint == null)
        {
    
    
            return false;
        }
        //尝试发送以非阻塞模式发送一个消息 注意这个非阻塞模式不会影响异步发送
        bool blockingState = client.Client.Blocking;
        try
        {
    
    
            byte[] tmp = new byte[1];
            client.Client.Blocking = false;
            client.Client.Send(tmp, 1, 0);
            return true;
        }
        catch (SocketException e)
        {
    
    
            // 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的  这个错误是说发送缓冲区已满或者客户端的接收缓冲区已满
            if (e.NativeErrorCode.Equals(10035))
                return true;
            else
                return false;
        }
        finally
        {
    
    
            client.Client.Blocking = blockingState; //恢复状态
        }
    }

Guess you like

Origin blog.csdn.net/weixin_44568736/article/details/130990283