2021-08-12 06:57:17 +01:00
|
|
|
# Simple test of a UDP server and client transferring data
|
|
|
|
|
|
|
|
import socket
|
|
|
|
|
|
|
|
NUM_NEW_SOCKETS = 4
|
2022-01-22 18:37:50 +00:00
|
|
|
NUM_TRANSFERS = 10
|
|
|
|
TOTAL_PACKETS = NUM_NEW_SOCKETS * NUM_TRANSFERS
|
|
|
|
# If more than 75% of packets are lost, the test fails.
|
|
|
|
PACKET_LOSS_THRESH = 0.75 * TOTAL_PACKETS
|
2021-08-12 06:57:17 +01:00
|
|
|
PORT = 8000
|
|
|
|
|
2022-01-22 18:37:50 +00:00
|
|
|
|
|
|
|
def print_stats(seq):
|
|
|
|
if (TOTAL_PACKETS - seq) > PACKET_LOSS_THRESH:
|
|
|
|
print(
|
|
|
|
"packet loss %.1f%% %d/%d"
|
|
|
|
% (((TOTAL_PACKETS - seq) / TOTAL_PACKETS * 100), seq, TOTAL_PACKETS)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
print("pass")
|
|
|
|
|
|
|
|
|
2021-08-12 06:57:17 +01:00
|
|
|
# Server
|
|
|
|
def instance0():
|
2022-01-22 18:37:50 +00:00
|
|
|
seq = 0
|
2021-08-12 06:57:17 +01:00
|
|
|
multitest.globals(IP=multitest.get_network_ip())
|
|
|
|
multitest.next()
|
|
|
|
for i in range(NUM_NEW_SOCKETS):
|
|
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
2022-01-18 21:50:53 +00:00
|
|
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
2022-01-22 18:37:50 +00:00
|
|
|
s.bind(socket.getaddrinfo("0.0.0.0", PORT + i)[0][-1])
|
|
|
|
s.settimeout(0.250)
|
2021-08-12 06:57:17 +01:00
|
|
|
multitest.broadcast("server ready")
|
|
|
|
for j in range(NUM_TRANSFERS):
|
2022-01-22 18:37:50 +00:00
|
|
|
try:
|
|
|
|
data, addr = s.recvfrom(1000)
|
|
|
|
except:
|
|
|
|
continue
|
|
|
|
if int(data) == seq:
|
|
|
|
if seq < (TOTAL_PACKETS - PACKET_LOSS_THRESH):
|
|
|
|
print(seq)
|
|
|
|
seq += 1
|
|
|
|
s.sendto(b"%d" % (seq), addr)
|
2021-08-12 06:57:17 +01:00
|
|
|
s.close()
|
|
|
|
|
2022-01-22 18:37:50 +00:00
|
|
|
print_stats(seq)
|
|
|
|
|
2021-08-12 06:57:17 +01:00
|
|
|
|
|
|
|
# Client
|
|
|
|
def instance1():
|
2022-01-22 18:37:50 +00:00
|
|
|
seq = 0
|
2021-08-12 06:57:17 +01:00
|
|
|
multitest.next()
|
|
|
|
for i in range(NUM_NEW_SOCKETS):
|
2022-01-22 18:37:50 +00:00
|
|
|
ai = socket.getaddrinfo(IP, PORT + i)[0][-1]
|
2021-08-12 06:57:17 +01:00
|
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
2022-01-22 18:37:50 +00:00
|
|
|
s.settimeout(0.250)
|
2021-08-12 06:57:17 +01:00
|
|
|
multitest.wait("server ready")
|
|
|
|
for j in range(NUM_TRANSFERS):
|
2022-01-22 18:37:50 +00:00
|
|
|
s.sendto(b"%d" % (seq), ai)
|
|
|
|
try:
|
|
|
|
data, addr = s.recvfrom(1000)
|
|
|
|
except:
|
|
|
|
continue
|
|
|
|
if int(data) == seq + 1:
|
|
|
|
if seq < (TOTAL_PACKETS - PACKET_LOSS_THRESH):
|
|
|
|
print(seq)
|
|
|
|
seq += 1
|
2021-08-12 06:57:17 +01:00
|
|
|
s.close()
|
2022-01-22 18:37:50 +00:00
|
|
|
|
|
|
|
print_stats(seq)
|