TCP Client & Server: A Working Pair

TCP Client & Server: A Working Pair in Python: You know how to open a socket. Now you need the piece nobody warns beginners about: TCP is a stream, not a…

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

StrategyHowUsed by
DelimiterEnd every message with \nSMTP, IRC, Redis
Length prefixSend 4 bytes of length, then the bodygRPC, most binary protocols
Fixed sizeEvery message is exactly N bytesSimple 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()
CallMeaning
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

  1. 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.
  2. Using send() instead of sendall(): send returns how many bytes it actually queued and may not send everything. sendall loops for you. There is almost no reason to use send.
  3. Forgetting SO_REUSEADDR: after the server stops, the OS holds the port in TIME_WAIT for a minute or two, so an immediate restart fails with "Address already in use."
  4. Reusing the listening socket to talk to a client: talk on the socket accept() returned, not the one you called listen() on.
  5. Interpreting empty recv as idle: b"" means closed, permanently. Looping on it without breaking spins the CPU at 100%.
  6. No timeout: sock.settimeout(5) prevents a client hanging forever on a server that stopped answering.
  7. Binding to 0.0.0.0 casually: that exposes your service on every network interface, including the public one. Use 127.0.0.1 unless you intend otherwise.
  8. 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 recv in a recv_exactly helper: partial reads are the rule, not the exception.
  • Use with on every socket: it closes on exception, and leaked sockets exhaust file descriptors.
  • Always sendall, never send.
  • Set SO_REUSEADDR and 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 asyncio past a few hundred connections: one thread per client stops scaling; asyncio.start_server handles thousands on one thread.
  • Prefer a higher-level protocol when you can: if you find yourself reinventing HTTP, use HTTP.

Practice Exercises

  1. 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.
  2. The File Transfer: Using length-prefixed framing, send a binary file from client to server and write it to disk. Verify with hashlib.sha256 that the two files match exactly.
  3. The Framing Demonstration: Write a client that sends b"AAA", b"BBB", and b"CCC" in three rapid sendall calls with no delimiter. Print exactly what each recv on the server returns, then explain in a comment why the output differs from what a beginner would expect.