Concept Explanation
You know how to open a socket. Now you need the piece nobody warns beginners about: TCP is a stream, not a sequence of messages.
When you call send(b"HELLO") and then send(b"WORLD"), the receiver might get b"HELLOWORLD" in one recv, or b"HELL" then b"OWORLD", or all ten bytes in three chunks. TCP guarantees the bytes arrive in order and complete. It guarantees nothing about where one call's data ends and the next begins.
Every real network protocol therefore defines a framing rule — a way to know where a message stops.
The Three Framing Strategies
| Strategy | How | Used by |
|---|---|---|
| Delimiter | End every message with \n | SMTP, IRC, Redis |
| Length prefix | Send 4 bytes of length, then the body | gRPC, most binary protocols |
| Fixed size | Every message is exactly N bytes | Simple sensor feeds |
Length-prefixing is the most robust: it handles binary data that might contain your delimiter, and the receiver knows exactly how many bytes to wait for.
The Server Lifecycle
socket() -> bind() -> listen() -> accept() -> recv/send -> close()
| Call | Meaning |
|---|---|
bind((host, port)) | Claim a port on this machine |
listen(backlog) | Start queueing incoming connections |
accept() | Block until a client arrives; return a new socket for it |
close() | Release |
The key insight in accept(): it returns a second socket. The listening socket keeps listening; the returned socket talks to that one client. Confusing the two is the most common beginner error.
The Client Lifecycle
socket() -> connect() -> send/recv -> close()
recv() Returns Empty When the Peer Hangs Up
data = conn.recv(1024)
if not data: # b"" means "the other side closed"
break # NOT "no data right now"
This is how you detect disconnection. An empty bytes object is an end-of-stream signal, not a timeout.
Code Example #1 (Basic)
A newline-delimited echo server and its client — the smallest correct pair.
# ---------- server.py ----------
import socket
HOST, PORT = "127.0.0.1", 9009
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
# Without this, restarting the server fails with "Address already in use"
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((HOST, PORT))
server.listen(5)
print(f"Listening on {HOST}:{PORT}")
conn, addr = server.accept() # blocks until a client connects
with conn:
print("Connected by", addr)
buffer = b""
while True:
chunk = conn.recv(1024)
if not chunk: # client disconnected
break
buffer += chunk
# Framing: process every COMPLETE line in the buffer
while b"\n" in buffer:
line, buffer = buffer.split(b"\n", 1)
text = line.decode("utf-8")
print(" received:", text)
conn.sendall(text.upper().encode("utf-8") + b"\n")
print("Client gone.")
# ---------- client.py ----------
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(5)
sock.connect(("127.0.0.1", 9009))
for message in ("hello", "sockets are streams", "bye"):
sock.sendall(message.encode("utf-8") + b"\n")
reply = sock.recv(1024).decode("utf-8").strip()
print(f"{message!r} -> {reply!r}")
Run the server in one terminal, the client in another. Notice the buffer loop: it accumulates bytes and only acts on complete lines. That is framing, and it is not optional.
Code Example #2 (Intermediate)
A length-prefixed, multi-client server using threads.
import socket
import struct
import threading
HOST, PORT = "127.0.0.1", 9010
def recv_exactly(sock, n):
"""recv() may return fewer bytes than asked. Loop until you have all n."""
buf = b""
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
return None # peer closed mid-message
buf += chunk
return buf
def send_message(sock, payload: bytes):
"""4-byte big-endian length, then the body."""
sock.sendall(struct.pack("!I", len(payload)) + payload)
def read_message(sock):
header = recv_exactly(sock, 4)
if header is None:
return None
(length,) = struct.unpack("!I", header)
if length > 10 * 1024 * 1024: # never trust a length from the network
raise ValueError("Message too large")
return recv_exactly(sock, length)
def handle_client(conn, addr):
with conn:
print(f"[+] {addr} connected")
try:
while True:
payload = read_message(conn)
if payload is None:
break
text = payload.decode("utf-8")
print(f" {addr}: {text}")
send_message(conn, f"ack: {text}".encode("utf-8"))
except (ConnectionResetError, ValueError) as err:
print(f"[!] {addr}: {err}")
finally:
print(f"[-] {addr} disconnected")
def serve():
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(16)
print(f"Serving on {HOST}:{PORT}")
while True:
conn, addr = server.accept()
# One thread per client -- fine to a few hundred; use asyncio beyond that
threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()
if __name__ == "__main__":
serve()
Three things here are what separate toy code from working code: recv_exactly loops because a single recv is never guaranteed to fill your buffer, the length header removes all ambiguity about message boundaries, and the size cap means a malicious client cannot make you allocate 4 GB by sending a fake length.
Common Mistakes
- Treating
recv(1024)as "one message": it returns up to 1024 bytes of whatever has arrived. Two sends can merge; one send can split. Always frame. - Using
send()instead ofsendall():sendreturns how many bytes it actually queued and may not send everything.sendallloops for you. There is almost no reason to usesend. - Forgetting
SO_REUSEADDR: after the server stops, the OS holds the port inTIME_WAITfor a minute or two, so an immediate restart fails with "Address already in use." - Reusing the listening socket to talk to a client: talk on the socket
accept()returned, not the one you calledlisten()on. - Interpreting empty
recvas idle:b""means closed, permanently. Looping on it without breaking spins the CPU at 100%. - No timeout:
sock.settimeout(5)prevents a client hanging forever on a server that stopped answering. - Binding to
0.0.0.0casually: that exposes your service on every network interface, including the public one. Use127.0.0.1unless you intend otherwise. - Trusting a length prefix: cap it. Otherwise a four-byte lie becomes a memory-exhaustion attack.
Best Practices
- Choose a framing rule before writing any protocol code: length prefix for binary, newline for text, and document which.
- Wrap
recvin arecv_exactlyhelper: partial reads are the rule, not the exception. - Use
withon every socket: it closes on exception, and leaked sockets exhaust file descriptors. - Always
sendall, neversend. - Set
SO_REUSEADDRand a timeout on every server — two lines that remove two whole categories of bug. - Use
struct.pack("!I", n)for headers: the!means network byte order, so a big-endian and a little-endian machine agree. - Reach for
asynciopast a few hundred connections: one thread per client stops scaling;asyncio.start_serverhandles thousands on one thread. - Prefer a higher-level protocol when you can: if you find yourself reinventing HTTP, use HTTP.
Practice Exercises
- The Chat Relay: Extend the threaded server so a message from one client is broadcast to all others. Keep a shared list of connections guarded by a
threading.Lock. - The File Transfer: Using length-prefixed framing, send a binary file from client to server and write it to disk. Verify with
hashlib.sha256that the two files match exactly. - The Framing Demonstration: Write a client that sends
b"AAA",b"BBB", andb"CCC"in three rapidsendallcalls with no delimiter. Print exactly what eachrecvon the server returns, then explain in a comment why the output differs from what a beginner would expect.