
# 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

```yaml
# 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:

```dart
@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));
}
```

```properties
chat.url=wss://chat.neon.books/ws
```

A server endpoint:

```dart
@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 `@WebSocketClient`** in the scanned package becomes a bean, named after the interface (`ChatSocket` → `chatSocket`). A client without a valid `ws://` or `wss://` URL, or with a method of another kind, stops the start.
- **Every abstract class with `@PhoenixChannel`** becomes a bean the same way: a channel of a Phoenix server, or of a service that speaks its protocol. The `phoenixSocketFactory` bean gives their sockets. See [Phoenix Channels client](phoenix.md).
- **A `webSocketTransport` bean**, `platformWebSocketTransport()`: `dart:io` on the VM and Flutter mobile and desktop, the browser's WebSocket on the web.
- **With the web starter:** every `@WebSocketEndpoint` and `WebSocketConfigurer` handler is mapped, a `WebSocketSessionRegistry` holds 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 in `springBootStarterWebsocketServerAutoConfiguration`, which is `native` only: where a server can run. A Flutter web app that uses the starter for its `@WebSocketClient`s carries no server code. See [Modules of one platform](../spring-core-dart-generator/optimizations/build-conditions.md#modules-of-one-platform).
- **At shutdown** every connection is closed; `closeAsync()` waits until they are.

## What is inside

- [Clients](clients.md): `@WebSocketClient`, `@OnMessage`, `@SendMessage`, the connection and reconnection.
- [Client configuration](client-configuration.md): `spring.websocket.client.*`, handshake interceptors, the transport and its limits.
- [Phoenix Channels client](phoenix.md): `@PhoenixChannel`, `@OnEvent`, `@Push`, many topics over one connection, `PhoenixSocket`.
- [Server endpoints](server-endpoints.md): `@WebSocketEndpoint`, `@OnOpen`, `@OnMessage`, `@OnClose`, `@OnError`.
- [Handlers, origins and broadcasting](handlers.md): `WebSocketHandler`, `WebSocketConfigurer`, `HandshakeInterceptor`, the origin check, `WebSocketSessionRegistry`.
- [Testing](testing.md): `MockWebSocketTransport` and `MockMvc.webSocket`.
- [All properties](properties.md): every key of the starter.
- [Differences from Spring](differences.md): 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.

## See also

- [WebSocket in the web starter](../spring-boot-starter-web/server/websocket.md)
- [spring_web_dart](../spring-web-dart/index.md)
- [spring_boot_starter_feign](../spring-boot-starter-feign/index.md)
- [Supabase Realtime](../spring-boot-starter-supabase/realtime.md)
- [What a build contains](optimizations.md)
