How to set timeout on python's socket recv method?
我需要在python的socket recv方法上设置超时。 怎么做?
典型的方法是使用select()等待数据可用或直到超时发生。仅在数据实际可用时调用
1 2 3 4 5 6 7 | import select mysocket.setblocking(0) ready = select.select([mysocket], [], [], timeout_in_seconds) if ready[0]: data = mysocket.recv(4096) |
如果你有很多打开的文件描述符,poll()是
另一种选择是使用
有
如上所述,
请注意,您可能需要根据需要拨打
1 2 3 4 5 6 7 8 9 10 | 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) |
您可以在收到响应之前设置超时,并在收到响应后将其设置回None:
1 2 3 4 5 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5.0) data = sock.recv(1024) sock.settimeout(None) |
您正在寻找的超时是连接套接字的超时而不是主套接字,如果您实现服务器端。换句话说,连接套接字对象有另一个超时,它是
1 2 3 4 5 | sock.listen(1) connection, client_address = sock.accept() connection.settimeout(5) # This is the one that affects recv() method. connection.gettimeout() # This should result 5 sock.gettimeout() # This outputs None when not set previously, if I remember correctly. |
如果您实现客户端,那将很简单。
1 2 | sock.connect(server_address) sock.settimeout(3) |
您可以使用
如前面的回复中所述,您可以使用类似:
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import socket s = socket.socket() s.settimeout(1) # Sets the socket to timeout after 1 second of no activity host, port ="somehost", 4444 s.connect((host, port)) s.send("Hello World! ") try: rec = s.recv(100) # try to receive 100 bytes except socket.timeout: # fail after 1 second of no activity print("Didn't receive data! [Timeout]") finally: s.close() |
我希望这有帮助!!
试试这个它使用底层C.
1 2 | timeval = struct.pack('ll', 2, 100) s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeval) |