1 year ago
#366171

Mint
Python UDP socket significant delay between packets
I'm writing a program to measure throughput between a client and a server. However, the transfer speed is extremely low, where there seems to be some kind of bottleneck in my algorithm that I'm not aware of (at least compared to the TCP counterpart that is over 4 times faster).
I tested with a few combinations of a 1MB message:
- 1024 x 1024 Byte messages: 5.661 Mbps (time delta = 1,481,729,239 ns)
- 2048 x 512 Byte messages: 2.965 Mbps (time delta = 2,829,176,990 ns)
- 4096 x 256 Byte messages: 1.464 Mbps (time delta = 5,731,879,418 ns)
The more messages with a smaller message size are sent, the worse the result (due to the accumulated latency).
I wonder what I might be doing wrong here, or whether if I could have done something differently?
Edit 1: I did some more testing and measurements, and I found out that the bottleneck is the line sock.recvfrom(message_size)
on the server.py
file, where there are huge delays between each recvfrom
but I don't know what is the reason behind it. I attempted to increase/decrease buffer size as well as adding sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1)
as suggested here but nothing changed.
Edit 2: I used Wireshark and found out that there is a massive delay between each packets sent for some reason. Most likely not the server's fault because I tested versus multiple hosts too.
The client.py
:
def tp_udp(host: str, port: int, message_size: int, message_count: int):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = f"{message_size} {message_count}"
sock.sendto(bytes(data, "utf-8"), (host, port))
message = os.urandom(message_size)
for i in range(0, message_count):
sock.sendto(message, (host, port))
sock.shutdown(socket.SHUT_RDWR)
sock.close()
The server.py
:
def tp_udp(port: int):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("", port))
try:
while True:
message_data, address = sock.recvfrom(1024)
message_data = message_data.decode("utf-8")
message_size = int(message_data.split(" ")[0])
message_count = int(message_data.split(" ")[1])
t1 = time.perf_counter_ns()
counter = 0
while counter < message_count:
sock.recvfrom(message_size)
counter += 1
t2 = time.perf_counter_ns()
typer.echo("[SERVER] All messages have been received")
time_delta = t2 - t1
throughput = (int(message_count) * int(message_size) * 10 ** 3 * 8) / time_delta
print(f"Time elapsed: {time_delta} ns")
print(f"Throughput: {round(throughput, 3)} Mbps")
except socket.error as error:
sock.shutdown(socket.SOCK_DGRAM)
sock.close()
python
sockets
udp
python-sockets
0 Answers
Your Answer