首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python udp客户端超时机器

python udp客户端超时机器
EN

Stack Overflow用户
提问于 2013-08-19 18:16:38
回答 1查看 23.3K关注 0票数 3

如果服务器套接字中生成的rand数小于4,我的客户套接字将在接收数据时挂起。我需要设置超时机制,允许客户套接字检测到有“超时”,然后它将继续发送消息。在运行服务器套接字和客户端套接字之后,显示了以下错误消息:

代码语言:javascript
复制
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

服务器插座:

代码语言:javascript
复制
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)

客户端套接字

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2013-12-20 17:53:10

那么,settimeout()会产生一个异常。试试这个:

代码语言:javascript
复制
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

希望这能有所帮助!

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18311338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档