如何检测套接字断开连接? /如何通过超时调用socket.recv? [英] How do I detect a socket disconnection? / How do I call socket.recv with a timeout?

查看:149
本文介绍了如何检测套接字断开连接? /如何通过超时调用socket.recv?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gevent修补套接字连接到流服务器,并且正在使用adsl连接.

I'm using gevent patched socket to connect to a streaming server and I'm using an adsl connection.

我不控制服务器,但是在测试中,如果我停止服务器,则可以通过仅检查recv的结果是否为空字符串来检测断开连接,但是如果我关闭自己的adsl调制解调器,则recv不会退出.如果我只是断开计算机的网络电缆的连接,它也不会返回空字符串,但是当我重新连接它时,它会返回同时发送的服务器的所有内容,因此我猜测路由器或调制解调器正在为我保持连接畅通并在我的网络电缆断开连接时缓冲流.

I don't control the server but in my tests, if I stop the server I can detect the disconnection by just checking if the result from recv is an empty string, but if I turn off my adsl modem recv never exits. If I just disconnect my computer's network cable it doesn't return an empty string either, but when I reconnect it, it returns everything the server sent in the meantime, so I'm guessing the router or modem is keeping the connection open for me and buffering the stream while my network cable is disconnected.

我尝试将socket.SO_RCVTIMEO设置为几秒钟,但未检测到断开连接,recv永远永远阻塞".这是gevent,因此它只会阻止greenthread,但我需要尽快检测到此断开连接,以便尝试重新连接.

I tried setting socket.SO_RCVTIMEO to a few seconds but it didn't detect the disconnection, recv continues to "block" forever. This is gevent, so it only blocks the greenthread, but I need to detect this disconnection as soon as possible so I can try to reconnect.

推荐答案

使用gevent提供的超时,例如在with语句中:

Use the timeouts provided by gevent, for example in a with-statement:

with Timeout(5, False):
    data = sock.recv()

或作为功能:

data = gevent.with_timeout(5, sock.recv, timeout_value="")

这篇关于如何检测套接字断开连接? /如何通过超时调用socket.recv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆