UDP Sockets & Datagram Communication
Unlike stream-oriented TCP, UDP (`SOCK_DGRAM`) is connectionless and message-oriented. Sockets dispatch independent datagrams via `sendto()` with zero 3-way handshake delays, ideal for real-time telemetry and metrics 📡.
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(("127.0.0.1", 9931))
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"METRIC_STATSD_EVENT", ("127.0.0.1", 9931))
data, addr = server.recvfrom(1024)
print(f"Datagram from {addr[0]}: {data.decode()} 📡")
server.close()
client.close()
# 10. UDP Sockets & Datagram Communication Unlike stream-oriented TCP, UDP (`SOCK_DGRAM`) is connectionless and message-oriented. Sockets dispatch independent datagrams via `sendto()` with zero 3-way handshake delays, ideal for real-time telemetry and metrics 📡. ```python import socket server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(("127.0.0.1", 9931)) client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.sendto(b"METRIC_STATSD_EVENT", ("127.0.0.1", 9931)) data, addr = server.recvfrom(1024) print(f"Datagram from {addr[0]}: {data.decode()} 📡") server.close() client.close() ``` Because UDP does not perform congestion control or packet ordering, modern web protocols like HTTP/3 build on QUIC (UDP with user-space encryption and reliable multiplexing), eliminating head-of-line blocking 🚀! --- ### Question What fundamental property differentiates UDP from TCP communication? 🧠- [ ] a. UDP preserves discrete message boundaries without establishing connection state or retransmission guarantees 📡 - [ ] b. UDP packets are limited to a maximum length of 8 bytes - [ ] c. UDP requires an active TLS handshake before sending - [ ] d. UDP sockets cannot run concurrently on multi-core systems --- ### Challenge Bind UDP socket on `('127.0.0.1', 9935)`. Send `b'PING_UDP'` from a client. Receive with `recvfrom(1024)`, close both, and print the decoded message. 🎯 <details> <summary>Solution</summary> ```python import socket srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) srv.bind(('127.0.0.1', 9935)) cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) cli.sendto(b'PING_UDP', ('127.0.0.1', 9935)) msg, _ = srv.recvfrom(1024) print(msg.decode()) srv.close() cli.close() ``` </details>