Video in progress

What is a frame in WebSocket, and how do text frames differ from binary frames?

A frame is the smallest unit of data in WebSocket: a small header (opcode, length, mask) and a payload. In a text frame the payload must be UTF-8 text; in a binary frame it can be any bytes.

📖 Answer

After the handshake, frames travel over the connection, not HTTP. The opcode tells you the frame type:

  • 0x1: text (JSON, and STOMP travels here);
  • 0x2: binary (images, protobuf, audio);
  • 0x8: close;
  • 0x9 / 0xA: ping / pong;
  • 0x0: continuation, when a large message is split into several frames.

The header is tiny, from 2 to 14 bytes. Compare that with the hundreds of bytes of headers in an HTTP request, and the difference is noticeable when you send small messages often.

In Spring this difference shows up in the handler types:

public class MyHandler extends AbstractWebSocketHandler {
    @Override
    protected void handleTextMessage(WebSocketSession s, TextMessage m) { /* text */ }

    @Override
    protected void handleBinaryMessage(WebSocketSession s, BinaryMessage m) { /* bytes */ }
}

If invalid UTF-8 is sent in a text frame, the receiver must close the connection with code 1007.