Video in progress
How does fragmentation (one message split into several frames) work in WebSocket, and how does a Spring handler receive the pieces?
The first frame of a message arrives with a text or binary opcode, the following ones with continuation (0x0), and the last one has the FIN bit set. By default Spring assembles the whole message; if supportsPartialMessages() returns true, the handler receives the pieces and checks isLast().
📖 Answer
The frame header has a FIN bit. FIN=1 means the final piece of the message. A large message can travel like this:
[opcode=0x1 FIN=0] {"items":[1,2,
[opcode=0x0 FIN=0] 3,4,5,
[opcode=0x0 FIN=1] 6]}
Control frames like ping/pong/close can slip in between the pieces, but another data message can't: only one fragmented message at a time per connection.
By default in Spring the container assembles the pieces in a buffer and the handler receives the whole message. The buffer is limited: on Tomcat the default is around 8 KB, and a larger message closes the connection with 1009. So if you expect large messages, you either enlarge the buffer with ServletServerContainerFactoryBean or work with the pieces:
public class UploadHandler extends BinaryWebSocketHandler {
@Override
public boolean supportsPartialMessages() { return true; }
@Override
protected void handleBinaryMessage(WebSocketSession s, BinaryMessage m) throws IOException {
sink(s).write(m.getPayload()); // piece straight to disk or a stream
if (m.isLast()) {
sink(s).close(); // the message is complete
}
}
}
This saves memory: a 50 MB message never sits in the heap as one piece. But piece boundaries don't line up with your data boundaries: you can't parse JSON from its middle, and a UTF-8 character can end up split across two pieces.
With STOMP this is a separate topic: a STOMP frame itself may arrive split across several WebSocket messages (for example, in @stomp/stompjs, if splitLargeFrames is enabled, a large frame is split into 8 KB chunks by default), and Spring's STOMP decoder assembles them up to messageSizeLimit.
Sign up to mark studied questions and save your progress.