Sockets and networking
A socket is one end of a network connection. A server creates a socket, binds it to an address and port, listens and accepts connections; a client connects to that address and sends bytes. Python's socket module exposes this directly. For everyday web work you'll use libraries such as httpx or FastAPI, which are built on sockets.
How a TCP connection works
| Server | Client |
|---|---|
socket() — create | socket() — create |
bind((host, port)) — claim an address | |
listen() — wait for callers | |
accept() — a client arrives | connect((host, port)) — call the server |
recv() / sendall() | sendall() / recv() |
close() | close() |
TCP guarantees that bytes arrive complete and in order. Data travels as bytes, so text is encoded with .encode() before sending and decoded with .decode() after receiving.
An echo server
import socket
HOST, PORT = "127.0.0.1", 5050
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((HOST, PORT))
server.listen()
print(f"Listening on {HOST}:{PORT}")
conn, addr = server.accept()
with conn:
print("Connected by", addr[0])
while data := conn.recv(1024):
conn.sendall(data.upper())A client
import socket
with socket.create_connection(("127.0.0.1", 5050)) as client:
client.sendall("hello, server".encode())
reply = client.recv(1024).decode()
print("Server replied:", reply)$ python server.py # terminal 1
Listening on 127.0.0.1:5050
Connected by 127.0.0.1
$ python client.py # terminal 2
Server replied: HELLO, SERVERAF_INETmeans IPv4 andSOCK_STREAMmeans TCP.127.0.0.1(localhost) is only reachable from your own computer — safe for experiments.recv(1024)returns up to 1024 bytes, and an empty result when the other side closes.SO_REUSEADDRlets you restart the server straight away without an "address in use" error.
Serving several clients
import socketserver
class UpperHandler(socketserver.StreamRequestHandler):
def handle(self) -> None:
for line in self.rfile:
self.wfile.write(line.upper())
if __name__ == "__main__":
with socketserver.ThreadingTCPServer(("127.0.0.1", 5050), UpperHandler) as server:
print("Serving many clients on port 5050")
server.serve_forever()socketserver.ThreadingTCPServer handles each client in its own thread, so one slow client doesn't block the others. For thousands of connections, asyncio.start_server does the same with coroutines.
HTTP is just text over a socket
import socket
request = (
"GET / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Connection: close\r\n\r\n"
)
with socket.create_connection(("example.com", 80)) as s:
s.sendall(request.encode())
response = b""
while chunk := s.recv(4096):
response += chunk
print(response.split(b"\r\n")[0].decode())HTTP/1.1 200 OK
Practice
Servers must parse what arrives. Write parse_request_line(line: str) that splits an HTTP request line such as "GET /learn/?page=2 HTTP/1.1" into method, path and version, and returns them as a tuple. Print the result, then just the path without the query string (the part before ?).
('GET', '/learn/?page=2', 'HTTP/1.1')
/learn/