简体   繁体   English

如何检测套接字断开? /如何在超时时调用socket.recv?

[英]How do I detect a socket disconnection? / How do I call socket.recv with a timeout?

I'm using gevent patched socket to connect to a streaming server and I'm using an adsl connection. 我正在使用gevent修补套接字连接到流媒体服务器,我正在使用adsl连接。

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. 我不控制服务器,但在我的测试中,如果我停止服务器,我可以通过检查recv的结果是否为空字符串来检测断开连接,但如果我关闭我的adsl调制解调器,则recv永远不会退出。 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. 如果我只是断开我的计算机的网络电缆,它也不会返回空字符串,但是当我重新连接它时,它会返回服务器在此期间发送的所有内容,所以我猜测路由器或调制解调器正在保持连接为我打开在我的网络电缆断开连接时缓冲流。

I tried setting socket.SO_RCVTIMEO to a few seconds but it didn't detect the disconnection, recv continues to "block" forever. 我尝试将socket.SO_RCVTIMEO设置为几秒钟,但它没有检测到断开连接,recv继续“阻止”永久。 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,所以它只阻止greenthread,但我需要尽快检测到这种断开连接,所以我可以尝试重新连接。

Use the timeouts provided by gevent, for example in a with-statement: 使用gevent提供的超时,例如在with语句中:

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

or as a function: 或作为一种功能:

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

it's not detecting the disconnection because there wasn't any disconnection, the TCP "connection" is still alive and suppose to be reliable. 它没有检测到断开,因为没有任何断开,TCP“连接”仍然存在并且假设是可靠的。 if for example you unplug your LAN cable, and the re-plug it, the connection will still work. 例如,如果拔下LAN电缆并重新插上,连接仍然可以正常工作。

if you really want to detect the disconnection ASAP, then i guess you should just parse every second the os network status (ifconfig/ipconfig)/ or use os events, and do what you want when you detect network disconnection. 如果你真的想尽快检测断开连接,那么我猜你应该每秒解析os网络状态(ifconfig / ipconfig)/或使用os事件,并在检测到网络断开连接时执行你想要的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM