I need to set timeout on python's socket recv method. How to do it?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- Multiple sockets for clients to connect to
- How to get the background from multiple images by
- Evil ctypes hack in python
As mentioned both
select.select()
andsocket.settimeout()
will work.Note you might need to call
settimeout
twice for your needs, e.g.You can use
socket.settimeout()
which accepts a integer argument representing number of seconds. For example,socket.settimeout(1)
will set the timeout to 1 secondYou could set timeout before receiving the response and after having received the response set it back to None:
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 thatrecv()
will never block indefinitely.select()
can also be used to wait on more than one socket at a time.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.try this it uses the underlying C.
there's
socket.settimeout()