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

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.

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.

See also