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

@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

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

In Spring (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