gpt4 book ai didi

python udp客户端超时机制

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

如果Server socket中生成的随机数小于4,我的client socket会暂停接收数据。我需要设置超时机制让client socket检测到“超时”,然后它会继续发送消息。在我运行服务器套接字然后运行客户端套接字后,出现如下错误消息:

Traceback (most recent call last):
File "E:\Studying\Python workspace\Client\src\Client.py", line 34, in <module>
data , addr = client.recvfrom(1024)
socket.timeout: timed out

服务器套接字:

import random
from socket import *
serverSocket = socket(AF_INET , SOCK_DGRAM)
serverSocket.bind(('', 15000))

while True:

rand = random.randint(0, 10)
message , address = serverSocket.recvfrom (1024)
message = message.upper()
print("received message: ", message)
print("echo to address: ", address)
print(rand)

if rand < 4:
continue
print("Sending message: ", message)
serverSocket.sendto(message, address)

客户端套接字

import socket

UDP_IP = "127.0.0.1"
RPORT = 15000
MESSAGE = "ping"

print("UDP target IP: ", UDP_IP)
print("UDP target port: ", RPORT)
print("message going to send: ", MESSAGE)

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

i=1

while True:
try:

if(i<11):
client.sendto(MESSAGE.encode('utf_8'),(UDP_IP, RPORT))
print("sending message: ", MESSAGE)
print(i)
i=i+1
client.settimeout(2)

data , addr = client.recvfrom(1024)
print("received echo: ", data)
print("received at: " , addr )

finally:
print("closing socket")
client.close()

最佳答案

好吧,settimeout() 会产生异常。试试这个:

while True:
try:
if(i<11):
client.sendto(MESSAGE.encode('utf_8'),(UDP_IP, RPORT))
print("sending message: ", MESSAGE)
print(i)
i=i+1
client.settimeout(2)

data , addr = client.recvfrom(1024)
print("received echo: ", data)
print("received at: " , addr )

except socket.timeout:
print("closing socket")
client.close()

如果您想了解有关 socket.settimeout() 的更多信息,请查看此链接: http://docs.python.org/2/library/socket.html#socket.timeout

希望对您有所帮助!

关于python udp客户端超时机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18311338/

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