c#判断socket是否还连接着

刚开始用的是Socket.Connected。但是,msdn上说:“

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.

 

所以不能用Socket.Connected判断。

使用方法:

private bool SocketConnected()
            {
                try
                {
                    return !_socket.Poll(1, SelectMode.SelectRead) && (_socket.Available == 0);
                }
                catch (SocketException)
                {
                    return false;
                }
                catch (ObjectDisposedException)
                {
                    return false;
                }
            } 


 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,可以通过Socket类的Connected属性来判断Socket是否已经连接或释放。如果Connected属性为true,表示Socket仍然连接着;如果Connected属性为false,表示Socket已经释放。 另外,还可以通过Socket类的Poll方法来检测Socket的状态。该方法可以检测Socket的状态,并返回一个布尔值,表示Socket是否可用。如果返回值为true,表示Socket可用;如果返回值为false,表示Socket不可用。 以下是一个示例代码,展示了如何使用Connected属性和Poll方法来判断Socket的状态: ```csharp Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint socket.Connect("127.0.0.1", 1234); // Check if the socket is connected if (socket.Connected) { Console.WriteLine("Socket is connected"); // Use the socket here... // Release the socket socket.Shutdown(SocketShutdown.Both); socket.Close(); // Check if the socket is released if (!socket.Connected && socket.Poll(0, SelectMode.SelectRead)) { Console.WriteLine("Socket is released"); } } else { Console.WriteLine("Socket is not connected"); } ``` 在上面的示例代码中,我们首先创建一个Socket对象,并使用Connect方法连接到一个远程地址。然后,我们使用Connected属性检测Socket是否连接成功。如果成功连接,我们就可以使用Socket对象进行通信。最后,我们使用Shutdown和Close方法释放Socket,并使用Connected属性和Poll方法检测Socket是否已经释放。如果已经释放,我们就可以在控制台输出相关信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值