python tcp连接状态判断_Socket套接字连接状态判断,接收数据笔记

最近工作中涉汲到一些Socket 方面应用 ,如断线重连,连接状态判断等,今天做了一些总结。1.判断Socket 连接状态通过 Poll 与 Connected 结合使用 ,重点关注SelectRead 模式方法名:Socket.Poll (int microSeconds, System.Net.Sockets.SelectMode mode) 方法参数:参数枚举:SelectRead如果已...
摘要由CSDN通过智能技术生成

最近工作中涉汲到一些Socket 方面应用 ,如断线重连,连接状态判断等,今天做了一些总结。

1.判断Socket 连接状态

通过 Poll 与 Connected 结合使用 ,重点关注 SelectRead  模式

方法名:

Socket.Poll (int microSeconds, System.Net.Sockets.SelectMode mode) 方法参数:

参数枚举:

SelectRead如果已调用 Listen(Int32) 并且有挂起的连接,则为 true。 - 或 - 如果有数据可供读取,则为 true。 - 或 - 如果连接已关闭、重置或终止,则返回 true; 否则,返回 false。

SelectWrite如果正在处理 Connect(EndPoint) 并且连接已成功,则为 true; - 或 - 如果可以发送数据,则返回 true; 否则,返回 false。

SelectError如果正在处理不阻止的 Connect(EndPoint),并且连接已失败,则为 true; - 或 - 如果 OutOfBandInline 未设置,并且带外数据可用,则为 true; 否则,返回 false。

SelectRead 模式返回 true 的三种情况,若Socket 处挂起状态 ,同时没有数据可读取,可以确定Socket 是关闭或终止的。

1.已调用 Listen(Int32) 并且有挂起的连接,则为 true

2.有数据可供读取,则为 true

3.如果连接已关闭、重置或终止,则返回 true

如下代码 ,true 表示连接断开

s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)  || !s.Connected

稍作调整,判断连接状态完整代码如下:

public static boolIsSocketConnected(Socket s)

{#region remarks

/*As zendar wrote, it is nice to use the Socket.Poll and Socket.Available, but you need to take into consideration

* that the socket might not have been initialized in the first place.

* This is the last (I believe) piece of information and it is supplied by the Socket.Connected property.<

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值