Learn / Advanced / Lesson 5

Sockets and networking

13 min Tested on Python 3.15Updated By
In short

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

ServerClient
socket() — createsocket() — create
bind((host, port)) — claim an address
listen() — wait for callers
accept() — a client arrivesconnect((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

server.py
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

client.py
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)
terminal
$ 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, SERVER
  • AF_INET means IPv4 and SOCK_STREAM means 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_REUSEADDR lets you restart the server straight away without an "address in use" error.

Serving several clients

multi_server.py
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

raw_http.py
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())
Output
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 ?).

Expected output:
('GET', '/learn/?page=2', 'HTTP/1.1')
/learn/
Your code

Quick check

1. What does server.accept() do?

2. Why call .encode() before sendall()?

3. What does an empty result from recv() mean?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →