Back
+20 XP
Concept

Reliable UDP with Sequence Numbers & Framing

Standard UDP drops packets silently under network congestion. Reliable UDP implements custom framing: prepending 4-byte sequence IDs (`struct.pack('!I', seq)`) so receivers can detect packet loss, reorder arrivals, and dispatch ACK receipts đŸ•šī¸.

python
import struct

def pack_udp(seq: int, data: bytes) -> bytes:
    # Header: 4-byte big-endian sequence counter
    return struct.pack("!I", seq) + data

def unpack_udp(raw: bytes):
    seq, = struct.unpack("!I", raw[:4])
    return seq, raw[4:]

packet = pack_udp(42, b"SNAPSHOT_DELTA")
seq_id, body = unpack_udp(packet)
print(f"Received Packet #{seq_id}: {body.decode()} đŸ•šī¸")

# 11. Reliable UDP with Sequence Numbers & Framing Standard UDP drops packets silently under network congestion. Reliable UDP implements custom framing: prepending 4-byte sequence IDs (`struct.pack('!I', seq)`) so receivers can detect packet loss, reorder arrivals, and dispatch ACK receipts đŸ•šī¸. ```python import struct def pack_udp(seq: int, data: bytes) -> bytes: # Header: 4-byte big-endian sequence counter return struct.pack("!I", seq) + data def unpack_udp(raw: bytes): seq, = struct.unpack("!I", raw[:4]) return seq, raw[4:] packet = pack_udp(42, b"SNAPSHOT_DELTA") seq_id, body = unpack_udp(packet) print(f"Received Packet #{seq_id}: {body.decode()} đŸ•šī¸") ``` If an outdated packet arrives after a newer state packet has already been processed (e.g. receiving player coordinate #34 after already rendering coordinate #38), reliable game engines can simply drop #34 without stalling the render thread đŸŽī¸! --- ### Question Why do low-latency multiplayer games build reliable UDP protocols instead of using standard TCP? 🧠 - [ ] a. TCP enforces head-of-line blocking: a single dropped packet freezes the whole stream, delaying newer positional updates đŸ•šī¸ - [ ] b. TCP sockets crash when bandwidth exceeds 10 megabits per second - [ ] c. UDP guarantees zero packet loss over satellite internet links - [ ] d. Operating systems disable TCP handshakes inside virtual machines --- ### Challenge Build `pack_udp(seq, data)`. Create a packet with `seq = 99` and `data = b'SYNC'`. Extract and print the 4-byte sequence number integer. đŸŽ¯ <details> <summary>Solution</summary> ```python import struct def pack_udp(seq: int, data: bytes) -> bytes: return struct.pack('!I', seq) + data pkt = pack_udp(99, b'SYNC') seq, = struct.unpack('!I', pkt[:4]) print(seq) ``` </details>

Checkpoint

Why do low-latency multiplayer games build reliable UDP protocols instead of using standard TCP? 🧠

Practice

Build `pack_udp(seq, data)`. Create a packet with `seq = 99` and `data = b'SYNC'`. Extract and print the 4-byte sequence number integer. đŸŽ¯

Terminal
01
Tap code blocks below to assemble
Available Blocks