UDP Pinger分配

时间:2018-05-28 04:59:26

标签: python networking server udp

我一直在尝试在python中编写UDP客户端/服务器(如底部所示)。 代码工作并运行。但是,我认为这条线路有问题:

    try:
        data, server = client_socket.recvfrom(1024) **# THIS LINE** 
        end = time.time()
        elapsed = end - start
        print(f'{data} {pings} {elapsed}')

当我运行代码时,它打印出计数器,当前时间和"请求时间输出"我想要的十倍。我不知道为什么!我做了很多研究并尝试了其他人的代码,但都没有工作!请帮忙!

服务器:

import random
from socket import *

serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', 12000))

while True:
    rand = random.randint(0, 10)    
    message, address = serverSocket.recvfrom(1024)
    message = message.upper()

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

客户:

import time
import socket

count = 0

for pings in range(10):
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    client_socket.settimeout(1.0)
    message = b'test'
    address = ("127.0.0.1", 12000)

    start = time.time()
    client_socket.sendto(message, address)

    count = count +1
    print(count, "\n", "current time: ", start)


    try:
        data, server = client_socket.recvfrom(1024)
        end = time.time()
        elapsed = end - start
        print(f'{data} {pings} {elapsed}')

    except socket.timeout:
        print('REQUEST TIMED OUT')

0 个答案:

没有答案