python recv timeout_如何在python的socket recv方法上设置超时?

如何在python的socket recv方法上设置超时?

我需要在python&#s套接字recv方法上设置超时。 怎么做?

8个解决方案

103 votes

典型的方法是使用select()等待数据可用或直到超时发生。 仅在数据实际可用时调用recv()。 为了安全起见,我们还将套接字设置为非阻塞模式,以保证socket.settimeout()永远不会无限期阻塞。 select()也可以用于一次等待多个套接字。

import select

mysocket.setblocking(0)

ready = select.select([mysocket], [], [], timeout_in_seconds)

if ready[0]:

data = mysocket.recv(4096)

如果您有大量打开的文件描述符,poll()是socket.settimeout()的更有效的替代方法。

另一种选择是使用socket.settimeout()为套接字上的所有操作设置超时,但我发现您在另一个答案中明确拒绝了该解决方案。

Daniel Stutzbach answered 2019-08-24T10:18:06Z

47 votes

那里是socket.settimeout()

nosklo answered 2019-08-24T10:18:34Z

24 votes

如前所述,settimeout和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)

ubershmekel answered 2019-08-24T10:19:08Z

11 votes

您可以在收到响应之前设置超时,并在收到响应后将其设置回None:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.settimeout(5.0)

data = sock.recv(1024)

sock.settimeout(None)

noriko answered 2019-08-24T10:19:35Z

4 votes

如果您实现服务器端,那么您要查找的超时是连接套接字超时而不是主套接字。 换句话说,连接套接字对象有另一个超时,它是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)

V123 answered 2019-08-24T10:20:11Z

1 votes

如前面的回复中所述,您可以使用类似:.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()

我希望这有帮助!!

petrexxy answered 2019-08-24T10:20:46Z

1 votes

您可以使用socket.settimeout(),它接受表示秒数的整数参数。 例如,socket.settimeout(1)将超时设置为1秒

Brian Zheng answered 2019-08-24T10:21:16Z

0 votes

试试这个它使用底层C.

timeval = struct.pack('ll', 2, 100)

s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeval)

Mohammad Alkhaldi answered 2019-08-24T10:21:44Z

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值