gpt4 book ai didi

Python:固定等待接收套接字数据的时间

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:22 24 4
gpt4 key购买 nike

我写了一个udp服务器和客户端。客户端向服务器发送简单的 udp 消息,服务器将响应。服务器会随机丢弃一些响应数据包。在我的客户端代码中,我写了以下行

for i in range(0,10):
sequence_number = i
start = time.time()
clientSocket.sendto("Ping " + str(i) + " " + str(start), server)
# Receive the client packet along with the address it is coming from
message, address = clientSocket.recvfrom(1024)
end = time.time()
if message != '':
print message
rtt = end - start
print "RTT = " + str(rtt)

如果服务器放弃响应,则以下行会卡在那里。

message, address = clientSocket.recvfrom(1024)

我在这里尝试了超时方法: Socket recv - limited wait time
但是超时将中止整个客户端程序。我只希望客户端等待 5 秒,然后在未收到最后一个响应(被服务器丢弃)的情况下继续发送下一个数据包。如何在客户端中设置等待时间?

最佳答案

settimeout() 的链接是正确的。超时时会引发异常。

Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode.

您需要将代码放在 try block 中,这样 Exception 就不会中止您的程序。

import socket.timeout as TimeoutException
# set timeout 5 second
clientsocket.settimeout(5)
for i in range(0,10):
sequence_number = i
start = time.time()
clientSocket.sendto("Ping " + str(i) + " " + str(start), server)
# Receive the client packet along with the address it is coming from
try:
message, address = clientSocket.recvfrom(1024)
except TimeoutException:
print("Timeout!!! Try again...")
continue
end = time.time()
if message != '':
print message
rtt = end - start
print "RTT = " + str(rtt)

关于Python:固定等待接收套接字数据的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37650716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com