C#的System.Net.Sockets.Socket类的Connected属性的一些细节


请尊重原作者的工作,转载时请务必注明转载自:www.xionggf.com

参考链接
https://blog.csdn.net/chy2z/article/details/80080549
http://technet.microsoft.com/zh-cn/magazine/system.net.sockets.socket.connected(VS.90).aspx

Connected的值不能作为当前TCP连接断开与否的判断依据

有时候客户端和服务端的依然处于正常连接状态,但Socket.Connected的值为false。这个值并不一定表示客户端已经和服务器断开连接。它仅表示Socket在上次Send操作,或者是Receive操作时有没有连接到远程主机(即服务器)。

如果要判断socket连接的当前状态,请调用非阻止性、零字节发送。如果调用成功返回或引发WAEWOULDBLOCK错误代码 (10035),则仍连接套接字;否则,无法再连接套接字。示例代码如下:

// .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);