判断socket是否是链接状态

/// <summary>
/// 当socket.connected为false时,进一步确定下当前连接状态
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
private bool IsSocketConnected(Socket client)
{
    #region remarks
    /********************************************************************************************
    * 当Socket.Conneted为false时, 如果您需要确定连接的当前状态,请进行非阻塞、零字节的 Send 调用。
    * 如果该调用成功返回或引发 WAEWOULDBLOCK 错误代码 (10035),则该套接字仍然处于连接状态; 
    * 否则,该套接字不再处于连接状态。
    * Depending on http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.connected.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
    ********************************************************************************************/
    #endregion

    #region 过程
    // This is how you can determine whether a socket is still connected.
    bool connectState = true;
    bool blockingState = client.Blocking;
    try
    {
        byte[] tmp = new byte[1];

        client.Blocking = false;
        client.Send(tmp, 0, 0);
        //Console.WriteLine("Connected!");
        connectState = true; //若Send错误会跳去执行catch体,而不会执行其try体里其之后的代码
    }
    catch (SocketException e)
    {
        // 10035 == WSAEWOULDBLOCK
        if (e.NativeErrorCode.Equals(10035))
        {
            //Console.WriteLine("Still Connected, but the Send would block");
            connectState = true;
        }

        else
        {
            //Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
            connectState = false;
        }
    }
    finally
    {
        client.Blocking = blockingState;
    }

    //Console.WriteLine("Connected: {0}", client.Connected);
    return connectState;

    #endregion
}

 

posted @ 2024-05-08 11:49  木子zzgxl  阅读(45)  评论(0编辑  收藏  举报