Changing my UDP server to take the same request multiple times

  for-loop, python, python-requests, udp, udpclient

I need the UDP_server to take the request("message") multiple times (5-6 time will be ok) to calculate the arithmetic mean of the recorded response times (the time required from the moment you send the message to the time the response arrives from server). Probably I can do that with a "for", but I don’t really know where to place it or to use it.

UDP_server code:

import socket
server_port = 21060
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('127.0.0.1', server_port))
print ('[SERVER] Listening at: {}'.format(server_socket.getsockname()))
while True:
    message, address = server_socket.recvfrom(65535)
    modified_message = str(len(str(message).split(",")))
    print ('[SERVER] The client at {}, originally sent: {}'.format(address, repr(message)))
    server_socket.sendto(bytes('Server is sending back: "{}".'.format(modified_message), encoding='utf8'), address)
server_socket.close()

UDP_client code:

import socket
import string
import random
from time import time

def random_string(length, chars=string.ascii_letters + string.digits):
    return ''.join(random.choice(chars) for x in range(length))

server_port = 21060
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

input_s = random_string(100)
sent_time = time()
client_socket.sendto(bytes(input_s, encoding='utf8'), ('127.0.0.1', server_port))
input_s_modified, address = client_socket.recvfrom(65535)
received_time = time()

print ('[CLIENT] Response from server {}, is: "{}"'.format(address, str(input_s_modified.decode('utf8'))))
client_socket.close()
print("Time response =", received_time - sent_time, 'seconds')

Source: Python Questions

LEAVE A COMMENT