How to set timeout on python's socket recv method?


Question

I need to set timeout on python's socket recv method. How to do it?

1
93
4/27/2010 5:51:46 AM

The typical approach is to use select() to wait until data is available or until the timeout occurs. Only call recv() when data is actually available. To be safe, we also set the socket to non-blocking mode to guarantee that recv() will never block indefinitely. select() can also be used to wait on more than one socket at a time.

import select

mysocket.setblocking(0)

ready = select.select([mysocket], [], [], timeout_in_seconds)
if ready[0]:
    data = mysocket.recv(4096)

If you have a lot of open file descriptors, poll() is a more efficient alternative to select().

Another option is to set a timeout for all operations on the socket using socket.settimeout(), but I see that you've explicitly rejected that solution in another answer.

111
5/23/2014 8:33:37 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon