spring_boot_starter_websocket
spring_boot_starter_websocket gives Spring for Dart WebSocket connections, on both sides. Clients are abstract classes with a method for incoming messages (@OnMessage) and one for sending (@SendMessage), injected like any bean; the connection opens when first needed and reconnects after a loss. Server endpoints are @WebSocketEndpoint beans, or Spring's WebSocketHandler with a WebSocketConfigurer, served by spring_boot_starter_web on its port.
Why
A WebSocket stays open, so the server can push messages the moment something happens: a chat message, a price, a notification. Handling one by hand means opening it, encoding and decoding every frame, and opening it again when the network drops. The starter does that work. The generator writes the code at build time, without reflection, and messages are read and written as JSON through the ObjectMapper of spring_core_dart. Clients work on the VM, in Flutter (mobile, desktop, web) and in the browser.
Setup
# pubspec.yaml
dependencies:
spring_boot_starter_websocket: ^0.9.0
spring_boot_starter_web: ^0.9.0 # only for server endpoints
dev_dependencies:
build_runner: ^2.17.0
spring_core_dart_generator: ^0.9.0 # required: writes the client implementations
spring_boot_starter_test: ^0.9.0 # MockWebSocketTransport, MockMvc.webSocket
test: ^1.33.0
One import: package:spring_boot_starter_websocket/spring_boot_starter_websocket.dart re-exports spring_boot_dart, spring_web_dart and spring_boot_starter_logging. The starter does not depend on the web starter, so a Flutter app that only has clients starts no server.
Example
A client:
@WebSocketClient('chat', url: r'${chat.url}')
abstract interface class ChatSocket {
@OnMessage()
Stream<ChatMessage> messages(); // incoming messages, read from JSON
@SendMessage()
Future<void> send(ChatMessage message); // sent as JSON
}
@Introspected()
class ChatMessage {
const ChatMessage({required this.from, required this.text});
final String from;
final String text;
}
@Service()
@Log()
class Chat {
Chat(this.socket); // the generated client, injected like any bean
final ChatSocket socket;
// Listening opens the connection; it reconnects while someone listens.
void start() => socket.messages().listen((m) => log.info('${m.from}: ${m.text}'));
Future<void> say(String text) => socket.send(ChatMessage(from: 'me', text: text));
}
chat.url=wss://chat.neon.books/ws
A server endpoint:
@WebSocketEndpoint('/ws/rooms/{room}', allowedOrigins: ['https://chat.example'])
class ChatEndpoint {
ChatEndpoint(this.sessions);
final WebSocketSessionRegistry sessions;
@OnMessage()
void message(@PathVariable() String room, ChatMessage message) =>
sessions.broadcast('/ws/rooms/{room}', message); // to every open session
}
What starts
- Every abstract class with
@WebSocketClientin the scanned package becomes a bean, named after the interface (ChatSocket→chatSocket). A client without a validws://orwss://URL, or with a method of another kind, stops the start. - Every abstract class with
@PhoenixChannelbecomes a bean the same way: a channel of a Phoenix server, or of a service that speaks its protocol. ThephoenixSocketFactorybean gives their sockets. See Phoenix Channels client. - A
webSocketTransportbean,platformWebSocketTransport():dart:ioon the VM and Flutter mobile and desktop, the browser's WebSocket on the web. - With the web starter: every
@WebSocketEndpointandWebSocketConfigurerhandler is mapped, aWebSocketSessionRegistryholds the open sessions, and the handshakes pass the web filters. - Two modules. The clients are in
springBootStarterWebsocketAutoConfiguration, on every platform. The server side (webSocketSessionRegistry,webSocketHandlerMapping) is inspringBootStarterWebsocketServerAutoConfiguration, which isnativeonly: where a server can run. A Flutter web app that uses the starter for its@WebSocketClients carries no server code. See Modules of one platform. - At shutdown every connection is closed;
closeAsync()waits until they are.
What is inside
- Clients:
@WebSocketClient,@OnMessage,@SendMessage, the connection and reconnection. - Client configuration:
spring.websocket.client.*, handshake interceptors, the transport and its limits. - Phoenix Channels client:
@PhoenixChannel,@OnEvent,@Push, many topics over one connection,PhoenixSocket. - Server endpoints:
@WebSocketEndpoint,@OnOpen,@OnMessage,@OnClose,@OnError. - Handlers, origins and broadcasting:
WebSocketHandler,WebSocketConfigurer,HandshakeInterceptor, the origin check,WebSocketSessionRegistry. - Testing:
MockWebSocketTransportandMockMvc.webSocket. - All properties: every key of the starter.
- Differences from Spring: what works differently than in Spring.
In Spring (Java)
Spring has no declarative WebSocket client: you write a handler and hand it to the imperative client, or use STOMP. This starter follows the style of @FeignClient instead. On the server, Spring registers a WebSocketHandler (supported here too) or Jakarta's @ServerEndpoint classes; @WebSocketEndpoint follows Jakarta's names on a singleton bean. STOMP is not supported yet.