Sockets and framing: messages on a byte stream

Introduction

Programs reach the network through sockets. A socket is a handle: you write bytes into it and read bytes out of it, and the operating system handles TCP, IP and the rest. Every web server, chat app and game uses them. Browsers cannot open raw sockets, so this course does not run them here. But a socket is only a byte pipe, and the real skill is to put messages into that pipe and get them back out. We do that with plain strings and loops.

How it works

A TCP server makes a socket, binds it to a port, listens, and accepts each client. A client makes a socket and connects to the server's address and port. After that both sides send and receive (recv) bytes. In Python this looks like the code below. It is shown for reading only; it needs a real network and cannot run in the browser.

server = socket.socket()
server.bind(("0.0.0.0", 9000))
server.listen()
client, address = server.accept()
data = client.recv(1024)
client.send(data)

The key fact is that TCP is a byte stream. If a client sends "hello" and then "world", the server may receive "helloworld" in one recv, or "hel" and "loworld" in two. TCP keeps the order and the bytes, not the boundaries. A program that wants messages must add framing. Two common ways:

  • A delimiter: end each message with a special mark such as a newline. The receiver collects bytes in a buffer and cuts at every mark. HTTP headers, SMTP and many text protocols work like this.
  • A length prefix: start each message with its length. The receiver reads the length, then waits until that many bytes are in the buffer. Binary protocols prefer this because the data may contain any byte.

Text must be turned into bytes before it is sent. UTF-8 does this: plain English letters take 1 byte, but accented letters take 2, many symbols 3 and emoji 4. So the length of a message in bytes can be larger than its length in characters, and a length prefix must count bytes:

text = "café €5"
data = text.encode("utf-8")          # characters become bytes for the wire
print("characters:", len(text))
print("bytes:", len(data))
print("first bytes:", list(data[:5]))
print("back again:", data.decode("utf-8"))
Open in compiler

Example

The example sends three messages with a two-digit length prefix, but the network cuts the stream into four odd pieces. The receiver keeps a buffer.

# Each message is sent as two digits of length, then the text.
stream = "05hello03abc02hi"
chunks = [stream[0:4], stream[4:9], stream[9:11], stream[11:]]   # the network cuts it any way it likes

buffer = ""
for chunk in chunks:
    buffer += chunk
    print("received", repr(chunk))
    while len(buffer) >= 2 and len(buffer) >= 2 + int(buffer[:2]):
        size = int(buffer[:2])
        print("  message:", buffer[2:2 + size])
        buffer = buffer[2 + size:]
print("left in the buffer:", repr(buffer))
Open in compiler

Line by line

  1. stream is what the sender writes: 05hello, 03abc and 02hi.
  2. chunks shows what the receiver gets: the cuts fall in the middle of a length and in the middle of a message.
  3. Each chunk is added to buffer. The while loop checks whether the buffer holds a full length prefix and a full message.
  4. If so, it prints the message and removes it from the buffer. If not, it waits for the next chunk.
  5. At the end the buffer is empty: every byte was part of a message.

Expected result

received '05he'
received 'llo03'
  message: hello
received 'ab'
received 'c02hi'
  message: abc
  message: hi
left in the buffer: ''

In the real world

Chat servers, game servers and databases all frame their messages. HTTP uses both ideas: headers end at a blank line, and the body length comes from a Content-Length header. WebSocket and TLS put a length in front of every frame. A bug seen again and again is a program that assumes one recv equals one message: it works in testing on one machine and fails on the real network when messages arrive stuck together or cut in two. Encoding bugs are just as common, for example counting characters instead of bytes for the length and cutting an accented letter in half.

Common mistakes

  • Assuming one send gives one recv. A stream has no message boundaries.
  • Counting characters instead of bytes for a length prefix, which breaks with accents and emoji.
  • Throwing away the buffer after a message, losing the start of the next one that came in the same chunk.
  • Forgetting that a length prefix itself can arrive in two pieces.

Best practices

  • Always keep a buffer between the socket and your message parser.
  • Pick a framing rule at the start and write it down as part of the protocol.
  • Encode and decode text as UTF-8 at the edges of your program, and count bytes for lengths.
  • Set a maximum message size so a bad length cannot make the server wait forever.

Summary

A socket is a byte pipe between two programs. TCP keeps the order of the bytes but not the boundaries of the messages, so protocols add framing with delimiters or length prefixes, and receivers keep a buffer for incomplete data. Text is encoded as UTF-8, where bytes can outnumber characters.

Quick check

1. Which call does a TCP server use to wait for a new client?
2. A client sends 'hello' and then 'world'. What can the server's recv return?
3. Why can a UTF-8 message be longer in bytes than in characters?
4. What is the job of a length prefix?

Key takeaways

  • A server calls socket, bind, listen and accept; a client calls socket and connect; both use send and recv.
  • One send does not equal one recv: a stream can deliver data in any pieces.
  • Text must be encoded to bytes (UTF-8), and the byte count can be larger than the character count.
  • Framing with a delimiter or a length prefix gives messages back; keep a buffer for the part not yet complete.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.