Handlers, origins and broadcasting
Besides @WebSocketEndpoint, Spring's lower-level style works: a WebSocketHandler object, registered for paths by a WebSocketConfigurer bean, with HandshakeInterceptors. Every handshake from a browser is checked against the endpoint's allowed origins. WebSocketSessionRegistry holds the open sessions, to send to all of them at once.
Why
Code ported from Spring keeps its handlers as they are, and one handler can serve several paths. The origin check keeps a page of another site from opening a connection with the user's cookies. Broadcasting to a room or to everyone is common enough to deserve a bean.
Example
// The echo handler answers on /ws/echo, for the shop's pages only.
@Configuration()
class WsConfig implements WebSocketConfigurer {
@override
void registerWebSocketHandlers(WebSocketHandlerRegistry registry) => registry
.addHandler(EchoHandler(), ['/ws/echo'])
.setAllowedOrigins(['https://shop.example'])
.setSupportedProtocols(['echo.v1'])
.addInterceptors([TokenInterceptor()]);
}
final class EchoHandler extends TextWebSocketHandler {
@override
void handleTextMessage(ServerWebSocketSession session, String text) =>
session.sendMessage('echo: $text (${session.attributes['token']})');
}
// Only clients with a token connect; the handler finds it in session.attributes['token'].
final class TokenInterceptor with HandshakeInterceptor {
@override
bool beforeHandshake(request, response, attributes) {
final token = request.queryParameters['token']?.firstOrNull;
if (token == null) return false; // 403
attributes['token'] = token; // becomes session.attributes
return true;
}
}
// Every client of /ws/news gets the announcement.
@Service()
class Announcer {
Announcer(this.sessions);
final WebSocketSessionRegistry sessions;
void announce(Object news) => sessions.broadcast('/ws/news', news); // as JSON
}
The types
| Type | Spring | What |
|---|---|---|
WebSocketHandler |
WebSocketHandler |
afterConnectionEstablished, handleMessage (String or Uint8List), handleTransportError, afterConnectionClosed. |
AbstractWebSocketHandler, TextWebSocketHandler |
the same | Text and binary messages in separate methods; a binary message closes a TextWebSocketHandler's connection (1003). |
WebSocketConfigurer, WebSocketHandlerRegistry |
the same | addHandler(handler, paths), then setAllowedOrigins, setAllowedOriginPatterns, setSupportedProtocols, addInterceptors. |
HandshakeInterceptor |
the same | beforeHandshake(request, response, attributes): false refuses (403, unless it answered itself); afterHandshake(request, error). |
ServerWebSocketSession |
server-side WebSocketSession |
id, handshakeHeaders, attributes, principal, pathVariables, isOpen, sendMessage, sendJson, close. |
WebSocketSessionRegistry |
none | The open sessions: sessions([pattern]), broadcast(pattern, message) (null: every endpoint). |
WebSocketHandlerMapping |
WebSocketHandlerMapping |
Maps the handshakes; the web starter's dispatcher asks it after the controllers. |
A session's incoming messages go to handleMessage: the server reads its messages stream itself, which can be listened to only once.
Differences from Spring
- An error a handler method throws goes to
handleTransportError, and the connection stays open unless the handler closes it; Spring closes it with 1011.AbstractWebSocketHandler.handleTransportErrordoes nothing, so override it to log or close. setAllowedOrigins,setAllowedOriginPatternsandsetSupportedProtocolsadd to the values set before; Spring's replace them.HandshakeInterceptors apply to the handlers of a configurer only, not to@WebSocketEndpoints; a web filter covers both.- No
@EnableWebSocketis needed.
Origins
As in Spring's OriginHandshakeInterceptor, a browser connecting from the server's own origin (the same scheme, host and port, a missing port being the scheme's default) is accepted; one from another origin only when the endpoint's rules allow it. Others get a 403. The rules are those of the web starter's CORS:
allowedOrigins/setAllowedOriginsare whole origins, compared without case ('https://chat.example');'*'allows any.allowedOriginPatterns/setAllowedOriginPatternsare compared with case:*matches any text ('https://*.chat.example'takeshttps://eu.chat.example, nothttps://chat.example;'*.chat.example'takes any scheme), and a port list at the end takes the ports listed ('http://localhost:[3000,3001]') or, with[*], any port or none.- A value may list several, separated by commas, and a trailing
/is ignored. - A client that sends no
Origin(an app, a server) is accepted: authenticate those with a filter or aHandshakeInterceptor.
Differences from Spring, none for what browsers send: an Origin longer than 1024 characters gets a 403 whatever the rules; the server's own origin is recognized whatever the case of its host; an Origin that is not a URL gets a 403 (Spring fails with a 500).
The endpoint's origins alone decide: the web starter's addCorsMappings rules and @CrossOrigin belong to the controllers and do not apply to a handshake. Only a CorsConfigurationSource bean named corsConfigurationSource with rules for the endpoint's path is checked too, by the security starter's filter, as Spring Security checks it.
Broadcasting
WebSocketSessionRegistry holds the open sessions per endpoint path, written as on the endpoint (/ws/rooms/{room}, not /ws/rooms/neon). A session joins when its handshake succeeds and leaves when it closes.
broadcast(pattern, message)sends aStringas text, bytes as binary and anything else as JSON, and skips a session that closed meanwhile.nullas the pattern sends to every endpoint.sessions([pattern])lists the open sessions, for example to send to one room: filter bysession.pathVariables['room']orsession.attributes.
With a pool of server isolates each isolate has its own registry, holding the sessions it accepted: broadcast reaches those, not the other isolates'. See Server endpoints.
Spring has no counterpart; a Spring application keeps such a list itself.