COMPUTER NETWORKS / 6. SOCKETS & WEBSOCKETS
Sockets & WebSockets
Raw network programming and real-time bidirectional communication
EXPLANATION
A socket is the OS abstraction for a network endpoint. It's a file descriptor connected to a network connection. All network communication — HTTP, SSH, DNS, everything — is built on sockets. The socket API (Berkeley sockets, invented in 1983, still unchanged): • socket() → create a new socket (specify AF_INET for IPv4, SOCK_STREAM for TCP) • bind() → attach socket to an IP:port (server side) • listen() → start accepting connections (server side, sets backlog queue size) • accept() → block until a client connects, return a new socket for that connection • connect() → initiate connection to server (client side, triggers TCP handshake) • send()/recv() → transmit/receive data • close() → close the connection (triggers TCP FIN) Blocking vs Non-blocking sockets: • Blocking (default): recv() blocks until data arrives. accept() blocks until a client connects • Non-blocking: operations return immediately with an error if they'd block • Async I/O (asyncio, select, epoll): efficient non-blocking I/O — one thread handles thousands of connections WebSockets — HTTP's upgrade to full-duplex communication: • HTTP is half-duplex: client requests, server responds. Client must request again for new data • WebSocket is full-duplex: once connected, either side can send at any time without the other requesting • Connection starts as HTTP, then upgrades: Client sends: "Upgrade: websocket" Server responds: "101 Switching Protocols" Now it's a persistent TCP connection with WebSocket framing • Used for: chat apps, live dashboards, collaborative editing, real-time games, live notifications FastAPI supports WebSockets natively with @app.websocket(). The client connects once and the server can push updates as events happen — no polling needed. Socket options: • SO_REUSEADDR → allow binding to a port that's in TIME_WAIT (essential for dev) • SO_KEEPALIVE → detect dead connections • TCP_NODELAY (Nagle's algorithm off) → send packets immediately (important for latency-sensitive apps)
DIAGRAM
TCP SOCKET LIFECYCLE: Server Client socket() socket() bind(8000) connect(server:8000) ─→ SYN listen() SYN-ACK ←────────────────────────── accept() ←─────────────────────────────── ACK [new socket] recv() ←───────────── data ──────────── send() send() ─────────────→ data ──────────── recv() close() ─────────────→ FIN ──────────── close() HTTP vs WEBSOCKET: HTTP (request-response): Client →→→ Request → Server Client ←←← Response ← Server Client →→→ Request → Server (must request again) Client ←←← Response ← Server WebSocket (full-duplex): Client ←──────────────────── Server push Client ───────────────────→ Client message Client ←──────────────────── Server push (both sides can send anytime, one persistent connection)
CODE