
# Clients

A WebSocket client is an abstract class marked `@WebSocketClient`, with a method that returns the incoming messages as a `Stream` (`@OnMessage`) and a method that sends one (`@SendMessage`). The generator implements it, and the container makes it a bean. The connection opens when first needed, is shared by all streams and sends of the client, and reconnects after a loss while someone listens.

## Why

An app that shows live data must open the socket, decode each frame, and open it again when the network drops, with a growing pause so a restarting server is not flooded. Declared as an interface, the socket is a typed stream and a typed send, and all of that is done for you.

## Example

```dart
@WebSocketClient('prices', url: r'${prices.url}', protocols: ['prices.v2'])
abstract interface class PriceSocket {
  @OnMessage()
  Stream<PriceUpdate> updates();         // JSON text messages

  @OnMessage()
  Stream<Uint8List> snapshots();         // binary messages

  @SendMessage()
  Future<void> subscribe(Subscription subscription);

  Future<void> connect();                // optional: open now
  Future<void> close();                  // optional: close early (code 1000)
}

@Service()
class Ticker {
  Ticker(this.socket);

  final PriceSocket socket;
  StreamSubscription<PriceUpdate>? _subscription;

  Future<void> watch(String isbn) async {
    _subscription = socket.updates().listen(show);   // opens the connection
    await socket.subscribe(Subscription(isbn: isbn));
  }

  Future<void> stop() async {
    await _subscription?.cancel();                   // the last listener: no more reconnects
    await socket.close();
  }
}
```

## @WebSocketClient

| Attribute | Meaning |
|---|---|
| `name` (positional) | The client's name: its properties are `spring.websocket.client.config.<name>.*`, and handshake interceptors see it as `clientName`. |
| `url` | The address, starting with `ws://` or `wss://`; `${...}` placeholders allowed. Without it, the `url` property. |
| `protocols` | Subprotocols offered in the handshake (`Sec-WebSocket-Protocol`). |

## Methods

| Method | What it does |
|---|---|
| `@OnMessage() Stream<T> name()` | The incoming messages. `String` gives the text messages as they are, `Uint8List` the binary messages, any other type the text messages read as JSON. Messages of the other kind are skipped. A message that cannot be read arrives as an error event (`MessageConversionException`), and the stream goes on. Every call gives a new stream; all streams see every message. |
| `@SendMessage() Future<void> name(T message)` | Sends a message: a `String` as text, a `Uint8List` (or a `List<int>` parameter) as binary, anything else as JSON text. Waits while the connection opens. Completes when the message is queued, not when it has left. |
| `Future<void> connect()` | Optional. Opens the connection now instead of on first use. |
| `Future<void> close()` | Optional. Closes the connection early (code 1000), on logout or when a screen goes away. The streams are done; using the client again opens a new connection. Not needed at shutdown. |

Any other method stops the application at startup with the reason, and so does a missing URL or one that does not start with `ws://` or `wss://`. A value a `@SendMessage` method cannot write as JSON throws a `MessageConversionException` from the call itself, before a `Future` is returned.

## The connection

- **One per client.** All streams and sends of a client share one connection.
- **On demand.** It opens on the first listener of an `@OnMessage` stream, on the first message sent, or on `connect()`.
- **Reconnection while someone listens.** A connection that was lost (closed with no code, 1001, 1005, 1006 or 1011 to 1014, or dropped by the client with 4500), or an attempt that failed, is opened again after a wait. The first wait is `reconnect.delay`; each further one is multiplied by `reconnect.multiplier`, up to `reconnect.max-delay`, give or take `reconnect.jitter`. Listeners stay subscribed meanwhile.
- **Sends during an outage.** A send (or `connect()`) waits for the next attempt only, and fails if that attempt fails, so it never waits longer than the delay plus `connect-timeout`. With listeners, reconnecting goes on after such a failure; without any, nothing more is tried.
- **Giving up.** The retries keep counting until a connection proves stable: it delivers a message or stays open for `reconnect.max-delay`. So a server that accepts and closes at once still reaches `reconnect.max-retries`. After giving up, the streams end with the last error; the next listener starts again with every retry. Once the last listener cancels, no further attempt is made.
- **Closed by the server.** A normal close (1000) ends the streams. Other codes (1008 policy violation...) end them with a `WebSocketException`.
- **Shutdown.** Connections are closed when the application stops; `closeAsync()` waits until they are.

The connection is managed by a `WebSocketConnectionManager`; the open connection is a `WebSocketSession` of `spring_web_dart`.

## In Spring (Java)

```java
WebSocketClient client = new StandardWebSocketClient();
client.execute(new TextWebSocketHandler() {
  @Override
  protected void handleTextMessage(WebSocketSession session, TextMessage message) { ... }
}, "wss://chat.neon.books/ws");
```

Spring has no declarative WebSocket client; `@WebSocketClient`, `@OnMessage` (on a client) and `@SendMessage` are this project's own. Spring's `WebSocketConnectionManager` does not reconnect; this one does. STOMP is not supported yet.

## See also

- [Client configuration](client-configuration.md)
- [Testing](testing.md)
- [spring_web_dart](../spring-web-dart/index.md)
