Server endpoints
With spring_boot_starter_web in the dependencies, a @WebSocketEndpoint bean accepts WebSocket connections to a path on the web server's port. Its methods are called when a connection opens (@OnOpen), for each message (@OnMessage), when it closes (@OnClose) and on errors (@OnError). The names follow Jakarta's @ServerEndpoint.
Why
A chat, a live dashboard or a game server needs to accept connections, read messages in order, reply, and push to everyone in a room. An endpoint bean says this in a few annotated methods, with constructor injection like any other bean. The handshake is an ordinary HTTP request, so it passes the web starter's filters, and a security filter authenticates it before the endpoint takes it.
Example
// A chat with one room per path: /ws/rooms/neon, /ws/rooms/dart...
@WebSocketEndpoint('/ws/rooms/{room}', allowedOrigins: ['https://chat.example'])
@Log()
class ChatEndpoint {
ChatEndpoint(this.sessions);
final WebSocketSessionRegistry sessions;
// The endpoint is shared by all connections: per-connection state goes in session.attributes.
@OnOpen()
void open(ServerWebSocketSession session, @PathVariable() String room, Principal? user) {
session.attributes['room'] = room;
session.attributes['user'] = user?.name ?? 'guest';
}
@OnMessage()
Ack message(@PathVariable() String room, ChatMessage message) {
sessions.broadcast('/ws/rooms/{room}', message); // to every open session of the endpoint
return Ack(room: room, received: message.text); // the reply, sent back as JSON
}
@OnClose()
void close(ServerWebSocketSession session, CloseStatus status) =>
log.info('${session.id} left: ${status.code}');
@OnError()
void error(ServerWebSocketSession session, Object error) =>
session.sendMessage('error: $error');
}
@Introspected()
class Ack {
const Ack({required this.room, required this.received});
final String room;
final String received;
}
@WebSocketEndpoint
| Attribute | Meaning |
|---|---|
path (positional) |
A path pattern, as on controllers ({room}, {*rest}). |
allowedOrigins |
Whole origins browsers may connect from (see Handlers, origins and broadcasting). |
allowedOriginPatterns |
Origin patterns (https://*.chat.example, http://localhost:[*]). |
protocols |
The subprotocols the endpoint speaks. The first one the client offers that is in the list is chosen; a client offering none of them still connects, without a protocol. |
name |
The bean's name. |
Method parameters
The methods take what they need, in any order:
| Parameter | Value |
|---|---|
ServerWebSocketSession (or WebSocketSession) |
The connection. |
@PathVariable() String room |
A {room} of the path (@PathVariable('id') for another name). An int, double, bool, enum... is converted by the ConversionService; a value that does not convert answers the handshake with 400. |
Principal? |
The user of the handshake (null when anonymous). |
the message, in @OnMessage |
String (text), Uint8List (binary), or any other type, read as JSON through the ObjectMapper. |
CloseStatus, in @OnClose |
Why the connection closed. |
the error, in @OnError |
What a method threw, or the connection's error. |
Behaviour
- Replies. What
@OnMessagereturns is sent back, after awaiting aFuture: aStringas text, bytes as binary, anything else as JSON.voidandnullsend nothing. - Order and back-pressure. The messages of one connection are handled one after the other, in order. While one is handled the connection is not read, so a client that sends faster than the handler works is held back by the network instead of filling the server's memory.
- Incoming size. A message larger than
server.websocket.max-text-message-sizeormax-binary-message-size(8 KB by default, as Tomcat's) closes the connection with 1009. - Slow readers. What is sent to a client that reads slowly waits in memory up to
server.websocket.send-buffer-size-limit(512 KB) andsend-time-limit(10 s); past either, the connection is dropped and@OnClosegets 4500 (CloseStatus.sessionNotReliable). A client that goes away meanwhile gets the session closed with 1006 (CloseStatus.noCloseFrame). Aftersession.close(status),@OnClosegets that status. Either way the session leavesWebSocketSessionRegistry. - Errors. An exception goes to the
@OnErrormethod, and the connection stays open. Without an@OnErrormethod, it is logged and the connection is closed with 1011 (server error). This holds for@OnOpentoo. Anything else that fails for a connection is logged tospring.websocket.serverand closes it with 1011; it never ends the process. - Turning a client away.
@OnOpenmay close the session itself:@OnClosethen gets the status, once. Messages the client sent before it saw the close may still reach@OnMessage; checksession.isOpenthere. - Not a handshake. A request to the path that is not a WebSocket handshake gets a 400 in plain text; a repeated or malformed
Sec-WebSocket-Keya 400 problem, anotherSec-WebSocket-Versiona 426. - Session ids are random UUIDs (
session.id), as in Spring.
Where the server side is
The server side of the starter is a module of its own, springBootStarterWebsocketServerAutoConfiguration: the webSocketSessionRegistry bean and the webSocketHandlerMapping that routes the handshakes. It is native only: in the build where dart:io exists (the Dart VM, an AOT executable, a Flutter app on a phone or a desktop), and not in a browser build, which could not run a server anyway. An application does nothing for it; the generator lists both modules. A test that builds a context by hand names both (see Testing).
With a pool of isolates
With server.isolates.count above one, every isolate of the web server's pool has its own endpoints and its own WebSocketSessionRegistry. A connection belongs to the isolate that took its handshake, for as long as it is open.
broadcastreaches the clients connected to the isolate that sends, not the others'. In a chat room whose members are spread over four isolates, a message is seen by about a quarter of them.sessions()lists the sessions of its isolate.- State an endpoint keeps in a field (who is in the room) is per isolate too.
- An isolate that leaves the pool closes its sessions; the clients connect again and reach another isolate.
The pool names the registry in the warning it logs when it first adds an isolate (Each isolate keeps its own WebSocket sessions in memory, ...). To reach every client, each isolate must hear of the message: publish it to something all isolates listen to (a message broker, a database notification), and let each one broadcast to its own sessions.
Checked at startup
Two handlers for one path, a @PathVariable that is not in the path or of a type nothing converts a String to, a parameter of none of the kinds above, several methods with the same annotation, or an endpoint without any of @OnOpen, @OnMessage and @OnClose stops the application with the list of problems.
Security
The handshake is an HTTP GET that passes the web filters: with spring_boot_starter_security, protect the path with a rule (requestMatchers('/ws/**').authenticated()), and the endpoint gets the user as Principal. Browsers cannot send headers on a handshake: they send the session cookie, or a token in the query.
In Spring (Java)
@ServerEndpoint("/ws/rooms/{room}")
public class ChatEndpoint {
@OnMessage
public void message(@PathParam("room") String room, String text, Session session) { ... }
}
Spring has no annotated endpoint of its own: it registers a WebSocketHandler, or Jakarta's @ServerEndpoint classes through a ServerEndpointExporter. Here the endpoint is a singleton bean with constructor injection (Jakarta creates one per connection), and @PathVariable replaces @PathParam. No @EnableWebSocket is needed.