Skip to content

Lesson 1 of 9 · 22m

TCP Sockets: The Byte-Stream Mental Model

TCP is an ordered byte pipe, not a message bus — learn what connect, send, recv, and close really mean before building anything on top.

The first production socket bug usually arrives as a mystery: a client sends a complete request, the server occasionally reads half of it, and somebody proposes adding sleep(0.1). That fix is cargo cult networking. TCP never promised to preserve your write boundaries. It promised an ordered, reliable stream of bytes — nothing more.

A socket is an endpoint, not a message queue

A TCP connection is identified by four values: local IP, local port, remote IP, remote port. Python exposes it through socket.create_connection() for clients and bind/listen/accept for servers.

import socket

with socket.create_connection(("127.0.0.1", 8080), timeout=5) as sock:
    sock.sendall(b"ping
")
    data = sock.recv(1024)

create_connection performs DNS resolution, tries candidate addresses, and applies a timeout to the connect operation. sendall keeps writing until the full bytes object is accepted by the kernel. recv(1024) returns up to 1024 bytes that are currently available — not one message, not one line, and not necessarily what the peer wrote in one call.

The kernel is buffering both directions

Your process does not write directly to the network. send copies bytes into the kernel send buffer; TCP then handles segmentation, acknowledgments, retransmission, and congestion control. On the other side, bytes sit in the peer kernel receive buffer until the application reads them. This is why network programs can deadlock even when the machines are healthy: both applications can be blocked writing while neither side is reading.

app A -> kernel A -> network -> kernel B -> app B
               ACKs/retransmits happen below you

A minimal server is accept-loop plus per-connection loop

import socket

srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 8080))
srv.listen(128)

while True:
    conn, addr = srv.accept()
    with conn:
        while chunk := conn.recv(4096):
            conn.sendall(chunk)

listen(128) is the backlog of connections waiting for accept, not the number of clients your service can support forever. SO_REUSEADDR avoids restart friction after a crash, but it is not permission to run two live services on the same port.

Half-closes are real

shutdown(socket.SHUT_WR) means "I am done writing, but I may still read." Protocols use this when a client finishes upload and still expects a final response. Simply closing the socket discards that distinction. An empty return from recv means the peer will send no more bytes; it does not mean the machine vanished or the network broke.

Field notes

  • Never use the length of one recv call as protocol evidence; accumulate bytes and parse frames.
  • Set timeouts before handing sockets to business logic; unbounded reads turn small outages into thread exhaustion.
  • send may transmit fewer bytes than requested. Use sendall unless you have a specific nonblocking design.
  • ConnectionResetError often means the peer closed while unread data was still queued, not that TCP itself is unstable.
  • Test with nc -l 127.0.0.1 8080 and nc 127.0.0.1 8080 before blaming your parser.

Was this lesson helpful?

Sign in to rate