开发者

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.

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开发者_C百科 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. 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.


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

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. if for example you unplug your LAN cable, and the re-plug it, the connection will still work.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜