Lab 14: Networking & Sockets

Objective

Master Python networking: raw TCP sockets with a request-response protocol, socketserver.ThreadingTCPServer for a multi-client echo service, http.server for a minimal HTTP server, urllib.request for HTTP GET/POST, and asyncio streams for an async TCP client-server pair — all on localhost.

Background

Every network library (requests, aiohttp, FastAPI) sits on top of the OS socket API. Understanding raw sockets demystifies connection handling, framing, and protocol design. Python's socketserver adds threading, and asyncio replaces threads with coroutines for non-blocking I/O. Production services use frameworks on top of these primitives, but knowing the layers helps you debug, tune, and design correctly.

Time

35 minutes

Prerequisites

  • Python Advanced Lab 05 (Advanced Async)

Tools

  • Docker: zchencow/innozverse-python:latest


Lab Instructions

Steps 1–8: Raw TCP echo, length-prefixed framing, ThreadingTCPServer, urllib HTTP, async TCP server, async client, concurrent requests, Capstone

💡 TCP is a stream, not a message protocol. A single send("hello world") might arrive as "hello" + " world" in two recv() calls. This is TCP stream semantics. To build a message protocol on top, you need framing — the most common approach is a 4-byte length prefix before each message. The receiver reads 4 bytes, learns the message size, then loops on recv() until it has all the bytes. HTTP uses Content-Length: and chunked encoding for exactly the same reason.

📸 Verified Output:


Summary

API
Layer
Use for

socket.socket()

Raw TCP

Protocols, debugging

struct length-prefix

Framing

Message boundaries

socketserver.ThreadingTCPServer

Threaded server

Simple multi-client

urllib.request

HTTP client

Stdlib HTTP (no deps)

asyncio.start_server

Async TCP

High-concurrency server

asyncio.open_connection

Async TCP client

Non-blocking connect

Further Reading

Last updated