Sub topic 9
Byte Stream versus Message Boundaries
This chapter assumes you know what a TCP segment is, how sequence numbers and acknowledgments give reliable, ordered delivery, and how a UDP datagram differs from a TCP connection. It also assumes basic Python socket code.
Two different promises
TCP and UDP hand data to your program in different shapes.
- UDP preserves message boundaries. Each
sendtoproduces one datagram. Eachrecvfromreturns exactly one whole datagram, or fails if your buffer is too small for it. - TCP provides a byte stream. It guarantees that bytes arrive in the order they were sent and without gaps. It does not remember where one
sendended and the next began.
TCP numbers every byte with a sequence number. The receiver only sees a continuous run of numbered bytes. The write calls that produced them leave no trace in that run.
Why boundaries disappear
TCP is free to repackage your data. The sender may:
- Combine small writes into one segment, which is what Nagle's algorithm does.
- Split a large write across several segments to fit the maximum segment size.
- Retransmit bytes inside a different segment than the one that first carried them.
The receiver may also see its data in pieces, because recv returns whatever is currently in the receive buffer, up to the size you asked for.
Seeing it in code
The client below sends two writes, half-closes its sending side, and then reads until the server closes. The server is the echo server from the sockets chapter, listening on port 9000.
import socket
with socket.create_connection(("127.0.0.1", 9000)) as s:
s.sendall(b"hello ")
s.sendall(b"world")
s.shutdown(socket.SHUT_WR)
chunks = []
while True:
data = s.recv(1024)
if not data:
break
chunks.append(data)
print(b"".join(chunks))The output is b'hello world'. The number of recv calls that return data may be one or more. Your code must not depend on that number.
shutdown(SHUT_WR) sends a FIN, which tells the peer that no more bytes are coming. The server's recv then returns an empty bytes object. The client can still read the echoed data afterward.
With UDP, the same two sendto calls would arrive as two separate datagrams, and the receiver would call recvfrom twice.
Common errors
- Assuming one
recvequals onesend. This works on a quiet loopback test and fails under load or on a real network. - Treating a short read as the end of the message. An empty result from
recvmeans the peer closed. A short result only means less data was available at that moment. - Using
sendwithout checking its return value.sendmay write only part of your data.sendallloops until everything is written or an error occurs. - Reading a UDP datagram into a buffer that is too small. The excess bytes are discarded.
Putting boundaries back
An application protocol on top of TCP must mark where messages end. The usual methods are:
| Method | How it works | Example |
|---|---|---|
| Delimiter | A special byte or sequence ends each message | HTTP/1.1 headers end with a blank line |
| Length prefix | A fixed-size length field comes before the payload | Many binary protocols |
| Fixed size | Every message has the same length | Simple custom protocols |
| Close | The sender closes the connection | Old HTTP/1.0 responses |
A length prefix is the most common choice for binary data. The helper below reads exactly n bytes and uses it to read one framed message.
import socket
import struct
def recv_exact(sock, n):
buf = bytearray()
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
raise ConnectionError("peer closed mid-message")
buf.extend(chunk)
return bytes(buf)
def send_msg(sock, payload):
sock.sendall(struct.pack("!I", len(payload)) + payload)
def recv_msg(sock):
(length,) = struct.unpack("!I", recv_exact(sock, 4))
return recv_exact(sock, length)The !I format means a 4-byte unsigned integer in network byte order.
Exercise
A client calls sendall(b"ABC") and then sendall(b"DEF") on a TCP connection. The server calls recv(1024) once and gets b"ABCDEF". Is this a bug in TCP? What would happen if the client had used UDP sendto twice, and what must the TCP application do to recover the two messages?
Show answer
It is not a bug. TCP delivers an ordered byte stream and does not preserve write boundaries, so the two writes may arrive in one read. With UDP, the two sendto calls would arrive as two separate datagrams, each returned whole by its own recvfrom (unless one is lost or reordered). Over TCP, the application must add framing, for example a length prefix or a delimiter, and read until a complete message is available.