How to use python socket.settimeout() properly

前端 未结 3 1048
自闭症患者
自闭症患者 2020-12-31 13:33

As far as I know, when you call socket.settimeout(value) and you set a float value greater than 0.0, that socket will raise a scocket.timeout when a call to, fo

3条回答
  •  醉梦人生
    2020-12-31 14:16

    Timeout applies to a single call to socket read/write operation. So next call it will be 20 seconds again.

    A) To have a timeout shared by several consequential calls, you'll have to track it manually. Something along these lines:

    deadline = time.time() + 20.0
    while not data_received:
        if time.time() >= deadline:
            raise Exception() # ...
        socket.settimeout(deadline - time.time())
        socket.read() # ...
    

    B) Any code that's using a socket with a timeout and isn't ready to handle socket.timeout exception will likely fail. It is more reliable to remember the socket's timeout value before you start your operation, and restore it when you are done:

    def my_socket_function(socket, ...):
        # some initialization and stuff
        old_timeout = socket.gettimeout() # Save
        # do your stuff with socket
        socket.settimeout(old_timeout) # Restore
        # etc
    

    This way, your function will not affect the functioning of the code that's calling it, no matter what either of them do with the socket's timeout.

提交回复
热议问题