PREP WITH PROOF
Menu
NETWORKING & PYTHON / PRACTICAL GUIDE

TCP Message Framing in Python: Handle Partial Reads and Length Prefixes

Build a bounded length-prefixed stream parser in Python. Handle fragmented headers, combined messages, empty payloads and truncated EOF with a tested local lab.

THE QUICK ANSWER

TCP carries an ordered byte stream, not application message boundaries. One recv call can return part of a message or bytes covering several messages. Define a framing rule, preserve incomplete input between reads, validate declared lengths before accepting payloads, and distinguish clean EOF from a truncated frame. The example below uses a four-byte unsigned big-endian payload length with a 1,024-byte payload limit.

Why one send is not one recv

Imagine a client sends a header followed by a JSON body, then sends another request. A server calls recv once and tries to parse everything returned as one JSON document. It can fail because it received only a prefix, or because it received the end of one document followed by the start of another. This is an illustrative programming mistake, not evidence of a particular network incident.

TCP segmentation and application read buffers do not share a guaranteed one-to-one boundary. Choosing a larger receive size does not add that guarantee. Neither a short read nor a brief lack of new data identifies the end of an application message.

The receiver needs a rule it can evaluate from the bytes. Once that rule is explicit, read sizes become an implementation choice. Our tests vary those sizes deliberately so that correctness depends on the framing contract rather than the convenient boundaries observed in one run.

Source: RFC 9293: TCP segmentation and application buffer boundaries ↗

Choose a framing contract before writing the receive loop

A fixed-width record can work when every message really has the same byte size. Delimiter framing can work for line-based text, provided escaping, maximum line length and embedded delimiters are defined. Connection-close framing is suitable only when the protocol deliberately uses the end of the sending direction to finish the data.

This guide chooses a length prefix because it can carry arbitrary bytes, including newlines and zero bytes. It is an invented teaching protocol, not the TCP header or an existing JSON-over-TCP standard. Both peers must implement the same byte order, length meaning and maximum size.

Field or eventContract in this guideReceiver behavior
HeaderFour-byte unsigned big-endian integerWait until all four bytes are available
LengthPayload bytes only; excludes the headerReject values above 1,024 before waiting for that body
PayloadExactly the declared number of bytesEmit one bytes value; preserve the next frame’s prefix
Zero lengthA valid empty application messageEmit b""; do not confuse it with socket EOF
Socket EOFrecv returns b""Accept only when no partial header or body remains
Framing failureParser is closed permanentlyStop using that parser and close the connection in the owner

Source: Python 3.12 Socket Programming HOWTO: message framing ↗

Measure bytes after encoding, not characters before encoding

The fixture includes the text water: 水 😀. Encoding it as UTF-8 produces a byte string whose length differs from the text’s character count. The frame function measures the resulting bytes. A header based on the original character count would cause the receiver to cut the payload at the wrong position.

Keep framing and payload interpretation separate. The parser returns bytes; a later application layer can decode a complete text payload with its chosen error policy, then parse JSON or another format. Decoding each arbitrary incoming chunk as UTF-8 can fail when a multi-byte character spans two reads.

One fixture payload contains an invalid standalone UTF-8 byte intentionally. It is valid under our binary framing contract and is returned unchanged. That does not make it valid text. If the application protocol requires UTF-8, validate that requirement after extracting the frame and before acting on its contents.

Carry incomplete state between reads

The Frames object has two states: it either needs a four-byte header or needs a known number of payload bytes. feed appends a bounded chunk and extracts as many complete frames as possible. When it cannot complete the current field, it retains those bytes for the next call.

The parser removes a complete header before waiting for its body. After emitting a payload, it returns to header mode and continues through any remaining bytes. This is what handles both fragmentation and coalescing: the same loop can process half a header, several complete frames, or a payload followed by another incomplete header.

Length validation happens as soon as the fourth header byte arrives. The test supplies three bytes of an oversized declaration, observes no message, then supplies the fourth and checks rejection. The implementation does not wait for an attacker’s claimed body or allocate a byte array of that declared length.

Run the complete parser and local socket lab

Save the program as framing_lab.py and run python framing_lab.py without optimization flags so assertions remain enabled. We ran the exact listing on Python 3.12.14 under Linux: all 329 checks passed. The socketpair calls used AF_UNIX stream sockets, not an internet-facing listener or a TCP/IP packet capture.

The deterministic tests try every possible two-chunk split of the fixture stream, including cuts inside headers and multi-byte text, then 200 seeded chunk schedules. They compare decoded messages with the original byte payloads. A second set stops at every prefix of the stream and checks that only complete frame boundaries permit clean EOF.

The final two tests use real connected local stream sockets. One sends the complete fixture and shuts down its sending direction; the receiver reads until clean EOF. The other sends a body with its last byte missing and checks the truncated-frame error. These tests exercise socket integration without claiming any particular packetization, latency or TCP retransmission behavior.

import random
import socket

MAX_PAYLOAD = 1024
MAX_CHUNK = 4096


def frame(payload):
    if not isinstance(payload, bytes):
        raise TypeError('payload must be bytes')
    if len(payload) > MAX_PAYLOAD:
        raise ValueError('payload too large')
    return len(payload).to_bytes(4, 'big') + payload


class Frames:
    def __init__(self):
        self.buffer = bytearray()
        self.needed = None
        self.closed = False

    def fail(self, message):
        self.closed = True
        self.buffer.clear()
        raise ValueError(message)

    def feed(self, chunk):
        if self.closed:
            raise ValueError('parser closed')
        if not isinstance(chunk, bytes):
            raise TypeError('chunk must be bytes')
        if len(chunk) > MAX_CHUNK:
            self.fail('chunk too large')
        self.buffer.extend(chunk)
        output = []
        while True:
            if self.needed is None:
                if len(self.buffer) < 4:
                    break
                self.needed = int.from_bytes(self.buffer[:4], 'big')
                del self.buffer[:4]
                if self.needed > MAX_PAYLOAD:
                    self.fail('declared payload too large')
            if len(self.buffer) < self.needed:
                break
            output.append(bytes(self.buffer[:self.needed]))
            del self.buffer[:self.needed]
            self.needed = None
        return output

    def finish(self):
        if self.closed:
            raise ValueError('parser closed')
        self.closed = True
        if self.needed is not None or self.buffer:
            self.buffer.clear()
            raise ValueError('truncated frame at EOF')


def receive_frames(sock):
    parser = Frames()
    while True:
        chunk = sock.recv(MAX_CHUNK)
        if not chunk:
            parser.finish()
            return
        yield from parser.feed(chunk)


checks = 0


def check(condition):
    global checks
    assert condition
    checks += 1


def rejects(action, message):
    try:
        action()
    except ValueError as error:
        check(message in str(error))
    else:
        raise AssertionError('expected rejection')


payloads = [b'hello', b'', 'water: 水 😀'.encode('utf-8'), b'\x00\xff\n']
wire = b''.join(map(frame, payloads))
# Each possible two-chunk split, including inside every header and UTF-8 value.
for cut in range(len(wire) + 1):
    parser = Frames()
    check(parser.feed(wire[:cut]) + parser.feed(wire[cut:]) == payloads)
    parser.finish()
    rejects(lambda: parser.feed(b''), 'closed')
rng = random.Random(90)
for _ in range(200):
    parser, received, position = Frames(), [], 0
    while position < len(wire):
        size = rng.randint(1, 11)
        received.extend(parser.feed(wire[position:position + size]))
        position += size
    check(received == payloads)
    parser.finish()
# EOF is clean only at a complete frame boundary.
boundaries, position = {0}, 0
for payload in payloads:
    position += len(frame(payload))
    boundaries.add(position)
for cut in range(len(wire)):
    parser = Frames()
    parser.feed(wire[:cut])
    if cut in boundaries:
        parser.finish()
        check(parser.closed)
    else:
        rejects(parser.finish, 'truncated')
parser = Frames()
check(parser.feed(frame(b'x' * MAX_PAYLOAD)) == [b'x' * MAX_PAYLOAD])
rejects(lambda: frame(b'x' * (MAX_PAYLOAD + 1)), 'large')
parser = Frames()
check(parser.feed(b'\xff\xff\xff') == [])
rejects(lambda: parser.feed(b'\xff'), 'declared')
check(not parser.buffer and parser.closed)
rejects(lambda: parser.feed(frame(b'ok')), 'closed')
rejects(lambda: Frames().feed(b'x' * (MAX_CHUNK + 1)), 'chunk')
# A valid prefix in a failing feed is not returned to the caller.
rejects(lambda: Frames().feed(frame(b'ok') + b'\xff' * 4), 'declared')
# Real local stream sockets: not a TCP/IP packetization experiment.
left, right = socket.socketpair()
with left, right:
    left.settimeout(1)
    right.settimeout(1)
    left.sendall(wire)
    left.shutdown(socket.SHUT_WR)
    check(list(receive_frames(right)) == payloads)
    print('local socket family:', left.family.name)
left, right = socket.socketpair()
with left, right:
    left.settimeout(1)
    right.settimeout(1)
    left.sendall(frame(b'abc')[:-1])
    left.shutdown(socket.SHUT_WR)
    rejects(lambda: list(receive_frames(right)), 'truncated')
print(f'PASS: {checks} checks; deterministic chunks and local stream sockets')

Source: Python 3.12 socket API: recv,sendall,socketpair and shutdown ↗

An empty message and end of input are different events

The empty payload in the fixture is encoded as four zero header bytes. The parser consumes that header and emits b"" as a complete application message. The socket receive loop treats b"" returned directly by recv as end of the incoming stream and calls finish instead.

EOF after two header bytes is a truncated header. EOF after a valid length but before the full body is a truncated payload. Both are errors under this protocol. EOF immediately after the last complete payload is clean. The prefix tests make those cases explicit instead of relying on whether the remote process happened to close quickly.

A peer can finish sending while still receiving. In the local test, shutdown(SHUT_WR) provides an orderly end to that sending direction. A production protocol must decide what responses or acknowledgments remain permissible; the framing parser itself does not implement that conversation state.

Source: Python 3.12 socket API: recv,sendall,socketpair and shutdown ↗

A size bound is useful, but it is not a complete resource policy

The example permits at most 1,024 payload bytes and accepts chunks up to 4,096 bytes. These are small teaching limits, not universal tuning advice. Because the previous incomplete frame and the next chunk are bounded, the parser does not accumulate an unlimited unfinished body.

That local bound does not limit everything an application can consume. A peer can send many valid frames, including empty ones. The caller can also keep every emitted payload forever by collecting the generator into a list. Our list calls are deliberate finite test assertions; an ongoing service needs backpressure, request limits and a bounded processing queue.

A valid length can still arrive very slowly. The local socket tests use one-second socket timeouts to avoid an indefinitely stuck fixture. That is not a complete end-to-end message deadline: a production owner needs an explicit time budget and a policy for partial messages, idle connections and cancellation. A timeout is not an alternative message delimiter.

sendall completes a write attempt, not a business transaction

The lab uses sendall to transmit the already framed bytes. Unlike a single send call, it continues attempting to send the provided data until completion or error. If it raises, the caller cannot infer from that exception how much reached the other side. Do not resend the entire request blindly on the same connection.

Even a successful write does not prove that the peer parsed, authorized or committed the requested action. Those guarantees require an application response and, where retries are possible, an appropriate request identity or idempotency policy. Framing only establishes where one candidate application message ends.

Keep a single coordinated owner for writes on a connection. Independently producing headers and bodies from several tasks without a serialization policy can interleave application bytes. A correct receive parser cannot reconstruct the intended requests from a sender that violated its own wire contract.

Source: Python 3.12 socket API: recv,sendall,socketpair and shutdown ↗

Reject framing errors without guessing a new boundary

After an oversized declaration or truncated EOF, the parser is closed and cannot accept further input. It clears retained bytes instead of searching for something that looks like another header. With arbitrary binary payloads, that kind of guessed resynchronization can reinterpret body bytes as a fresh message.

The teaching API returns a list per successful feed call. If that call encounters a malformed frame after an otherwise complete prefix, it raises and does not return the prefix list. Frames returned by earlier calls are unaffected. The lab tests this behavior explicitly; the API does not provide transactional rollback of application actions or a delivery guarantee for a valid prefix followed by corruption.

When integrating receive_frames, let the connection owner close the socket on framing errors, socket exceptions or abandoned iteration. The generator does not own the supplied socket. A real service also needs authentication, transport protection and payload validation appropriate to its protocol; a numeric length is not evidence that a request is trusted.

Test boundaries instead of trying to reproduce one lucky read pattern

When a parser works locally but fails under load, record safe diagnostics such as bytes buffered, declared length and parser state. Avoid assuming a receive count corresponds to a message count. Reproduce the suspected boundary using controlled input splits, including one-byte header chunks and multiple complete frames in one chunk.

The local socketpair experiment is intentionally limited. It does not test TCP over a real network, TLS, resets, nonblocking readiness, concurrent producers, throughput or hostile-client load. Its value is a repeatable check that the framing algorithm survives arbitrary chunk schedules and rejects incomplete input.

Choose the wire contract first, keep its state across reads, and interpret payloads only after their boundary is known. That separates a transport symptom from a parser error and gives both sides a precise protocol to implement.

KEEP THESE THREE THINGS

Your next steps

  1. Treat TCP input as a byte stream with arbitrary read boundaries.
  2. Define byte order,length meaning,empty-message policy and size limits.
  3. Retain incomplete data and extract all complete frames.
  4. Reject truncated EOF and stop using a failed parser.
  5. Handle deadlines,backpressure,ownership and application acknowledgments separately.

Sources & official resources

Linked resources checked on 2026-11-03. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →