Network Programming with Sockets
Talk to the network directly, one byte at a time, with the socket module
socket module is Python's thin wrapper over the operating system's BSD sockets API. Everything higher up — HTTP clients, asyncio, web frameworks, database drivers — is ultimately built on these calls. Knowing them demystifies the whole stack.
- create a TCP socket and understand
AF_INET/SOCK_STREAM, - walk a server through
bind->listen->acceptand a client throughconnect, - send and receive bytes (never
str) and handle partial reads, - frame messages so a byte stream becomes discrete messages,
- build a minimal echo/chat server and reason about its trade-offs.
1. What a socket actually is
A socket is an operating-system object — a file-like handle — that represents one end of a network conversation. You create one by naming an address family and a socket type:
import socket
# AF_INET -> IPv4 addressing (host, port)
# SOCK_STREAM -> TCP: an ordered, reliable byte stream
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
The pair (host, port) is the address. The host is an IP address such as "127.0.0.1" (this machine) or "0.0.0.0" (every interface); the port is a 16-bit number (0–65535) that lets one machine host many independent services at once. A connection is uniquely identified by the four-tuple (local ip, local port, remote ip, remote port), which is why one server port can serve thousands of clients simultaneously.