c#判断socket是否还连接着

根据MSDN的说明,Socket.Connected属性只能反映最后一次I/O操作时的连接状态,不能用于实时判断当前连接是否有效。为了准确检查Socket是否仍然连接,应该执行一个非阻塞的、发送零字节的Send尝试。如果该操作成功或返回WAEWOULDBLOCK错误(10035),则表示Socket仍处于连接状态;反之,则表明连接已断开。
摘要由CSDN通过智能技术生成

刚开始用的是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;
                }
            } 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值