WebSocket transport
A WebSocket is a connection that stays open so both sides can send messages at any time: chat, live updates, games. WebSocketTransport.connect(url) opens one and returns a WebSocketSession, whose incoming messages are a Stream. The declarative client on top of it, an interface with @WebSocketClient, comes from spring_boot_starter_websocket.
Why
dart:io and the browser have different WebSocket classes, with different limits and errors. One interface over both, with Spring's send limits and close statuses, lets the same code run on a server, in a Flutter app and on the web, and lets tests replace the network.
Example
final sockets = platformWebSocketTransport();
final session = await sockets.connect(
Uri.parse('wss://chat.neon.books/ws'),
headers: HttpHeaders({'Authorization': 'Bearer $token'}), // not on the web
timeout: const Duration(seconds: 5),
);
session.messages.listen(log.info);
session.sendMessage('{"text":"hi"}');
await session.close(); // CloseStatus.normal; to say why:
// await session.close(CloseStatus.policyViolation.withReason('no token'));
Transports
| Transport | Platforms | Import |
|---|---|---|
platformWebSocketTransport(maxTextMessageSize:, maxBinaryMessageSize:) |
picks one of the two below | package:spring_web_dart/spring_web_dart.dart |
IoWebSocketTransport |
VM, Flutter on Android, iOS and desktop (dart:io WebSocket) |
package:spring_web_dart/io.dart |
BrowserWebSocketTransport |
web, Flutter web (WebSocket through dart:js_interop) |
package:spring_web_dart/browser.dart |
MockWebSocketTransport |
tests | package:spring_web_dart/testing.dart, or spring_boot_starter_test |
WebSocketSession
| Member | Meaning |
|---|---|
messages |
The incoming messages: a String for a text frame, a Uint8List for a binary one. |
sendMessage(message) |
A String (text) or a List<int> (binary). Does not wait. |
acceptedProtocol |
The subprotocol the server picked. |
isOpen |
Whether the session is open. |
close([status]) |
Closes it, with CloseStatus.normal by default. |
closeStatus |
How it closed. |
flush() |
IoWebSocketSession only: waits until what was sent has left. |
CloseStatus has constants (normal, goingAway, policyViolation, noCloseFrame 1006, sessionNotReliable 4500...), withReason(text) and equalsCode(other).
Sending and back-pressure
sendMessage does not wait: the message waits in memory until the network takes it. On dart:io (IoWebSocketSession, on both the client and the web starter's server), a session gives up when more than 512 KB wait or what was sent has not left within 10 seconds, as Spring's ConcurrentWebSocketSessionDecorator does: the connection is dropped and closeStatus is 4500. So a loop that sends faster than the network takes ends in 4500. Await flush() after each message to go at the network's pace:
// A large export, sent as fast as the server reads it.
final session = await IoWebSocketTransport().connect(url) as IoWebSocketSession;
for (final chunk in export) {
session.sendMessage(chunk);
await session.flush(); // fails with a WebSocketException if the connection ends
}
Set other limits with IoWebSocketTransport(sendBufferSizeLimit:, sendTimeLimit:).
Receiving
- A message from the server larger than 8 KB (text or binary, Tomcat's default) is not read on
dart:io: the session is closed with 1009 (message too big). The text limit counts UTF-8 bytes. Raise it withIoWebSocketTransport(maxTextMessageSize:, maxBinaryMessageSize:)orplatformWebSocketTransport(maxTextMessageSize: ...)(-1: no limit); the browser has none. - The connection goes on being read while messages wait to be sent, so two sides that both send a lot do not wait for each other.
- A connection that breaks ends
messages, withcloseStatus1006 and the error as the reason. - A ping between the fragments of a message is answered at once and the message arrives whole.
- A session closed before anyone listened still gives
messagesthat end once the close is done.
The handshake
- Browsers send no custom headers with the handshake, so
BrowserWebSocketTransportfails whenheadersis not empty. On the web, pass a token as a query parameter or as a protocol. - The handshake fails when the server picks a subprotocol the client did not offer or any extension (none is offered, so messages are not compressed), as RFC 6455 asks.
- A redirect is not followed, as in browsers.
In Spring (Java)
WebSocketSession session = new StandardWebSocketClient()
.execute(handler, "wss://chat.neon.books/ws").get();
WebSocketSession hands out the incoming messages as a Stream, where Spring calls a WebSocketHandler. sendMessage takes a String or bytes instead of a TextMessage or BinaryMessage, and does not block (Spring's does): use flush(). closeStatus tells how the session closed, which Spring passes to afterConnectionClosed.