Highlights

Contents

Part X
10

Socket programming and I/O

Packets become useful only when a server process reads and interprets their bytes. Without bounded admission and correct partial-I/O handling, a healthy network can still produce stuck workers or truncated messages. We will follow socket ownership, implement framing, and compare waiting threads with readiness-driven event loops.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Network models andphysical signals2Data link and Ethernetswitching3VLANs and IP addressing4IP forwarding and routing5Transport and TCP6Flow and congestioncontrol7DNS and HTTP8QUIC, TLS and websessions9Proxies, tunnels andfirewalls10Socket programming andI/O11CDN, P2P and cloudnetworking12The complete browserrequest

#Section 47Socket programming, buffers and partial I/O

A server binds and listens, then accepts separate connected sockets while retaining its listener. A file descriptor is a process-local handle naming the accepted kernel object.

The client creates a socket, connects to the destination, sends data, receives the response and closes. Socket buffers separate application calls from wire transmission. A successful send can accept fewer bytes than requested, and a receive can return only the currently available prefix. TCP’s byte-stream contract requires application framing, such as a known length, delimiter or protocol parser.

ONE LISTENER ACCEPTS CONNECTIONS WITH DISTINCT REMOTE ENDPOINTSONE LISTENER ACCEPTS CONNECTIONS WITH DISTINCT REMOTE ENDPOINTSserver processlistening socketclient Aclient Baccepted Aaccepted B
Figure 2.52The listener admits a connection, then the accepted descriptor owns its stream. Orange marks accept, where one listening endpoint becomes a separate conversation.

A short framed reader keeps reading until the requested byte count arrives or the stream closes. The caller must validate the advertised length before allocating memory. This example reads an already validated 1,460 byte teaching payload; it does not implement HTTP or TLS parsing.

python
def read_exact(sock, count):
    data = bytearray()
    while len(data) < count:
        chunk = sock.recv(count - len(data))
        if not chunk:
            raise EOFError("incomplete message")
        data.extend(chunk)
    return bytes(data)

The listening backlog limits pending admission under implementation-defined queue rules; it is not the application’s active-worker count. A blocking socket waits inside a call. A non-blocking socket reports that it cannot progress now, and the application arranges another attempt after readiness. Both must handle errors, orderly EOF and deadlines.

Leaving every connection open exhausts descriptors and buffer memory even if the CPU is idle. Closing a descriptor also needs clear ownership when several tasks reference it. Linux’s socket interface documents the system-call boundary. For an interview, distinguish listener state, established transport state, buffered bytes and application message state before proposing a server architecture.

#Section 48Blocking, non-blocking and asynchronous I/O

A blocking request can delay unrelated students when it occupies the only worker. Threads or pools change ownership, but blocking every bounded worker still stops progress.

Non-blocking I/O lets a call report that it would wait instead of suspending its caller. A readiness event says an operation may now make progress. An event loop waits for these events and advances each connection’s stored parsing and writing state. Readiness does not promise a complete application message, and the operation must still handle a short result or a changed condition.

THE EVENT LOOP SELECTS READY SOCKETS FROM A LARGER REGISTERED SETTHE EVENT LOOP SELECTS READY SOCKETS FROM A LARGER REGISTERED SETregistered socketsready subsetloopper-stream statereadiness permits progress; a whole message may still be incomplete
Figure 2.53Waiting threads keep individual call stacks, while a readiness loop stores per-connection progress. Orange marks epoll’s ready subset rather than treating every open socket as active work.

select represents watched descriptors in bounded sets, while poll accepts a descriptor array. epoll on Linux and kqueue on BSD systems maintain kernel-side registrations and report relevant events through their respective interfaces. Asynchronous completion I/O instead reports a submitted operation’s result; readiness and completion are different contracts.

An event loop can handle many idle sockets with relatively few threads because idle network waiting does not require a blocked thread per socket. It does not execute arbitrary CPU work in parallel on one loop. A blocking database call, long computation or unbounded callback can still delay every connection sharing it. Offload such work or use a compatible asynchronous interface.

Finch’s packet still has 1,460 payload bytes irrespective of whether a thread or loop reads it. The architectural change affects scheduling and ownership, not transport message boundaries. The epoll documentation describes readiness and edge-triggered handling. Edge-triggered readers normally drain until the socket would block; otherwise an unread remainder can wait without another edge.