我需要在python的socket recv方法上设置超时。怎么做?
答案 0 :(得分:104)
典型的方法是使用select()等待数据可用或直到超时发生。仅在数据实际可用时调用recv()
。为了安全起见,我们还将套接字设置为非阻塞模式,以确保recv()
永远不会无限期地阻塞。 select()
也可以用于一次等待多个套接字。
import select
mysocket.setblocking(0)
ready = select.select([mysocket], [], [], timeout_in_seconds)
if ready[0]:
data = mysocket.recv(4096)
如果你有很多打开的文件描述符,poll()是select()
的一种更有效的替代方法。
另一种选择是使用socket.settimeout()
为套接字上的所有操作设置超时,但我看到你在另一个答案中明确拒绝了该解决方案。
答案 1 :(得分:47)
答案 2 :(得分:24)
如前所述,select.select()
和socket.settimeout()
都可以使用。
请注意,您可能需要根据需要致电settimeout
两次,例如
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)
答案 3 :(得分:11)
您可以在收到响应之前设置超时,并在收到响应后将其设置回无:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5.0)
data = sock.recv(1024)
sock.settimeout(None)
答案 4 :(得分:4)
您正在寻找的超时是连接套接字的超时而不是主套接字,如果您实现服务器端。换句话说,连接套接字对象有另一个超时,它是socket.accept()
方法的输出。因此:
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.
如果您实施客户端,那将很简单。
sock.connect(server_address)
sock.settimeout(3)
答案 5 :(得分:2)
如先前的答复所述,您可以使用类似.settimeout()
的内容
例如:
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!\r\n")
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()
我希望这会有所帮助!
答案 6 :(得分:1)
您可以使用socket.settimeout()
来接受表示秒数的整数参数。例如,socket.settimeout(1)
会将超时设置为1秒
答案 7 :(得分:1)
#! /usr/bin/python3.6
# -*- coding: utf-8 -*-
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.settimeout(5)
PORT = 10801
s.bind(('', PORT))
print('Listening for broadcast at ', s.getsockname())
BUFFER_SIZE = 4096
while True:
try:
data, address = s.recvfrom(BUFFER_SIZE)
except socket.timeout:
print("Didn't receive data! [Timeout 5s]")
continue
答案 8 :(得分:0)
尝试使用底层C。
timeval = struct.pack('ll', 2, 100)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeval)
答案 9 :(得分:0)
大声喊叫:https://boltons.readthedocs.io/en/latest/socketutils.html
它提供了一个缓冲套接字,它提供了许多非常有用的功能,例如:
.recv_until() #recv until occurrence of bytes
.recv_closed() #recv until close
.peek() #peek at buffer but don't pop values
.settimeout() #configure timeout (including recv timeout)
答案 10 :(得分:0)
最热门的答案有些混乱,因此I've wrote a small gist带有一些示例,可以使您更好地理解。
选项1-socket.settimeout()
如果sock.recv()
等待的时间超过了定义的超时时间,则会引发异常。
import socket
sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.settimeout(timeout_seconds)
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = sock.recv(4096)
data = sock.recv(4096) # <- will raise a socket.timeout exception here
选项2-select.select()
等待直到发送数据直到达到超时为止。我已对Daniel's answer进行了调整,因此它将引发异常
import select
import socket
def recv_timeout(sock, bytes_to_read, timeout_seconds):
sock.setblocking(0)
ready = select.select([sock], [], [], timeout_seconds)
if ready[0]:
return sock.recv(bytes_to_read)
raise socket.timeout()
sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = recv_timeout(sock, 4096, timeout_seconds)
data = recv_timeout(sock, 4096, timeout_seconds) # <- will raise a socket.timeout exception here