python udp client time out machinsm

守給你的承諾、 提交于 2021-01-27 11:29:12

问题


My client socket would suspend in receving data if the rand number generated in Server socket less than 4. I need to set up time out mechanism to allow client socket detect there is "time out" and then it would continue send message. After I run the server socket and then the client socket, an error message showed below:

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

Server Socket:

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)

Client Socket

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()

回答1:


Well, settimeout() yields an exception. Try this:

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()

If you want more information on socket.settimeout(), check this link: http://docs.python.org/2/library/socket.html#socket.timeout

Hope that helps!



来源:https://stackoverflow.com/questions/18311338/python-udp-client-time-out-machinsm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!