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


0

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


Share
asked 12 Aug 2022 06:34:26 PM
junaidakhtar

No comment found


Answers

0

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.


Share
answered 12 Aug 2022 06:34:55 PM
junaidakhtar

No comment found


Share
answered 12 Aug 2022 06:35:29 PM
junaidakhtar

No comment found

0

As mentioned both select.select() and socket.settimeout() will work.

Note you might need to call settimeout twice for your needs, e.g.

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("",0))
sock.listen(1)
# accept can throw socket.timeout
sock.settimeout(5.0)
conn, addr = sock.accept()

# recv can throw socket.timeout
conn.settimeout(5.0)
conn.recv(1024)

Share
answered 12 Aug 2022 06:35:58 PM
junaidakhtar

No comment found


You must log in or sign up to answer this question.