How to test for a broken connection of TCPClient after being connected?

前端 未结 6 1543
-上瘾入骨i
-上瘾入骨i 2020-12-14 03:08

I\'ve been fighting with one problem for a whole 3 days I can\'t find any solution, please help :)
I work with Visual Studio 2010 and C# language.

I have a devic

6条回答
  •  有刺的猬
    2020-12-14 03:58

    I think this is a question that often comes around. This might be why MSDN docs really give a good answer to this - see Socket.Connected

    Quote from there:

    The Connected property gets the connection state of the Socket as of the last I/O operation. When it returns false, the Socket was either never connected, or is no longer connected.

    The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

    with this sample code:

    // .Connect throws an exception if unsuccessful
    client.Connect(anEndPoint);
    
    // This is how you can determine whether a socket is still connected.
    bool blockingState = client.Blocking;
    try
    {
        byte [] tmp = new byte[1];
    
        client.Blocking = false;
        client.Send(tmp, 0, 0);
        Console.WriteLine("Connected!");
    }
    catch (SocketException e) 
    {
        // 10035 == WSAEWOULDBLOCK
        if (e.NativeErrorCode.Equals(10035))
            Console.WriteLine("Still Connected, but the Send would block");
        else
        {
            Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
        }
    }
    finally
    {
        client.Blocking = blockingState;
    }
    
     Console.WriteLine("Connected: {0}", client.Connected);
    

    and the straight forward motification for an extension-method:

    public static bool IsConnected(this Socket client)
    {
       // This is how you can determine whether a socket is still connected.
       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;
       }
    }
    

提交回复
热议问题