捕获python套接字中的超时错误

时间:2021-03-27 13:28:49

标签: python sockets udp

try:
    data, addr = socket.recvfrom(64)
    pkts += 1
    split = data.split(b' ')
#     print(split)
#     print(sequence_num)
#     print(checksum)
    # Retransmit if packet was not ack or if checksum is
    # different (packet was corrupted)
    while int(split[0]) != sequence_num or int(split[1]) != checksum:
#       print('while loop running')
       socket.sendto(line.encode(), addr)
       data, addr = socket.recvfrom(64)
       split = data.split(b' ')
       corrupted_pkts += 1
       socket.sendto(line.encode(), addr)

    # To alternate the sequence number for each pkt
    if sequence_num == 0:
        sequence_num = 1
    else:
        sequence_num = 0
# Catches timeout error in the case of lost acks
except socket.timeout:
    socket.sendto(line.encode(), ('localhost', int(port_num)))

这是我的代码片段,试图在我的套接字超时时进行捕获。套接字设置为超时 50 毫秒,并且正在发送和接收 UDP 数据报。

我在尝试捕获超时错误时遇到问题,我收到 TypeError: catching classes that do not inherit from BaseException is not allowed 有什么办法可以通过强制 socket.timeout 从 BaseException 继承来解决此问题吗?任何其他解决方案也将不胜感激,目前,我可以在网上找到的所有内容都表明它应该可以像我的代码一样工作。

0 个答案:

没有答案