views:

724

answers:

4

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

A: 

The documentation is a good place to start.

zdav
+1  A: 

there's socket.settimeout()

nosklo
A: 

it sets timeout for the whole process (for listen, accept, etc) but i do need it only for recv.

Thoreller
ummm... so call it after the listen and accept are completed?
msw
+1  A: 

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 gaurantee 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.

Daniel Stutzbach
use `select` is good, but the part where you say "you can't" is misleading, since there is `socket.settimeout()`.
nosklo
@nosklo I've updated my answer.
Daniel Stutzbach
It's better now, but I don't see where the answer was "explicitly rejected".
nosklo