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

标签 python sockets

我写了一个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/

相关文章:

python - 使用 openpyxl 编辑电子表格。无法写入单元格, "cell is read-only error"

c++ - 如何过滤epoll事件?

sockets - 使用太多文件句柄打开 MPI 和 Boost MPI

Python 欺诈检测分类算法

java - AndroidManifest.xml 'package.name.Activity' 不可分配给 'android.app.Activity'

java - DatagramPacket.getAddress().getHostName() 正在阻塞我的线程

c - 如何使用 fork() 通过服务器连接两个客户端

python - 服务器脱机时如何保持代码在客户端上运行

python - 使用 Selenium 在 Flexbox 中查找元素

python - 为什么我的 dlib.get_frontal_face_detector() 的输出(矩形[])是空的?