WebSockets
suggest changeA WebSocket is a long-lived, two-way connection between a client and a server. It starts as an ordinary HTTP GET request with an Upgrade: websocket header. If the server agrees, it answers 101 Switching Protocols and from then on both sides can send messages at any time over the same TCP connection, without the request/response pattern of HTTP.
Use WebSockets when the server needs to push data to the client as it happens, or when both sides talk a lot:
- chat, notifications, multiplayer games, collaborative editing
- live dashboards, stock prices, progress of long jobs
- a Flutter app that needs updates without polling a REST API
If the server only pushes and the client never talks back, Server-Sent Events over plain HTTP are simpler. If the client asks and the server answers, plain HTTP is simpler still.
Dart has WebSocket support in three places:
| Library | Platforms | Use it for |
|---|---|---|
dart:io (WebSocket, WebSocketTransformer) |
VM, Flutter mobile and desktop | servers and clients without extra packages |
package:web_socket_channel |
VM, Flutter (all), browser | cross-platform clients, and the type Shelf hands you on the server |
package:web_socket |
VM, Flutter (all), browser | a newer, minimal client API with typed events |
On the server, package:shelf_web_socket turns a WebSocket endpoint into a normal Shelf handler.
This article covers:
- an echo server and client with
dart:io - text vs binary messages and close codes
- Shelf servers with
shelf_web_socketand routing - a chat room that broadcasts JSON messages
- authentication, subprotocols and checking
Origin - handling connection errors, and reconnecting with backoff
- detecting dead connections with pings
- the
package:web_socketAPI - WebSockets from Dart in the browser
- common mistakes
Packages used:
dart pub add shelf shelf_router shelf_web_socket web_socket_channel web_socket http
The examples were run with Dart 3.13, shelf 1.4.3, shelf_router 1.1.5, shelf_web_socket 3.0.0, web_socket_channel 3.0.3, web_socket 1.0.1 and http 1.6.0. Every server binds to port 0 so the OS picks a free port, and the client runs in the same program, so each example can be run as is.
Echo server and client with dart:io
WebSocketTransformer.upgrade() turns an HttpRequest into a WebSocket. WebSocket.connect() is the client side. A WebSocket is both a Stream of incoming messages and a StreamSink for outgoing ones, so you read with listen or await for and write with add:
import 'dart:io';
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
print('Listening on ws://localhost:${server.port}/ws');
server.listen((HttpRequest req) async {
if (req.uri.path != '/ws' || !WebSocketTransformer.isUpgradeRequest(req)) {
req.response
..statusCode = HttpStatus.notFound
..close();
return;
}
final ws = await WebSocketTransformer.upgrade(req);
print('server: client connected');
ws.listen(
(message) {
// message is a String for text frames, List<int> for binary frames
print('server got ${message.runtimeType}: $message');
ws.add(message is String ? 'echo: $message' : message);
},
onDone: () => print('server: closed ${ws.closeCode} ${ws.closeReason}'),
);
});
// Client
final client = await WebSocket.connect('ws://localhost:${server.port}/ws');
client.add('hello');
client.add([1, 2, 3]); // List<int> is sent as a binary frame
var received = 0;
await for (final message in client) {
print('client got $message');
if (++received == 2) {
await client.close(WebSocketStatus.normalClosure, 'bye');
}
}
print('client: closed ${client.closeCode} ${client.closeReason}');
await server.close();
}
Output:
Listening on ws://localhost:50644/ws
server: client connected
server got String: hello
server got _Uint8ArrayView: [1, 2, 3]
client got echo: hello
client got [1, 2, 3]
server: closed 1000 bye
client: closed 1000 bye
Things to notice:
- Each
addsends one complete message. WebSockets are message based, not byte-stream based, so you never have to split or join messages yourself. - Adding a
Stringsends a text frame (always UTF-8). Adding aList<int>sends a binary frame. On the receiving side text arrives asStringand binary as aUint8List, so check the type withis. WebSocketTransformer.isUpgradeRequest()lets the sameHttpServerserve normal HTTP requests and WebSockets.close(code, reason)starts the closing handshake. Both sides see the samecloseCodeandcloseReasononce the stream is done.
Close codes
The close code tells the other side why the connection ended. The common ones:
| Code | Name in WebSocketStatus |
Meaning |
|---|---|---|
| 1000 | normalClosure |
finished normally |
| 1001 | goingAway |
server shutting down, browser tab closed, or (in dart:io) ping timeout |
| 1002 | protocolError |
protocol violation |
| 1005 | noStatusReceived |
the peer closed without a code (never send it yourself) |
| 1006 | abnormalClosure |
connection dropped without a close frame (never send it yourself) |
| 1008 | policyViolation |
message violated the server's policy |
| 1009 | messageTooBig |
message too large |
| 1011 | internalServerError |
server hit an unexpected error |
| 3000-3999 | registered with IANA for libraries and frameworks | |
| 4000-4999 | free for your application |
package:web_socket_channel 3.x and package:web_socket follow the browser rule: you may only send 1000 or a code in 3000-4999. Anything else throws ArgumentError: Invalid argument: 1012, close code must be 1000 or in the range 3000-4999. Use 4000-4999 for application reasons such as "kicked" or "server restarting".
Servers with shelf_web_socket
webSocketHandler() from shelf_web_socket returns a Shelf Handler. It performs the upgrade and calls your callback with a WebSocketChannel and the negotiated subprotocol (or null). A WebSocketChannel has a stream for incoming messages and a sink for outgoing ones.
On the client side, WebSocketChannel.connect() from web_socket_channel works on every platform. It returns immediately; await channel.ready waits until the handshake succeeds and throws if it fails:
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
Future<void> main() async {
final handler = webSocketHandler((WebSocketChannel ws, String? protocol) {
ws.stream.listen((message) {
ws.sink.add('echo: $message');
});
});
final server = await shelf_io.serve(handler, 'localhost', 0);
print('Serving at ws://localhost:${server.port}');
final channel =
WebSocketChannel.connect(Uri.parse('ws://localhost:${server.port}'));
await channel.ready; // throws if the connection can't be established
channel.sink.add('one');
channel.sink.add('two');
final replies = await channel.stream.take(2).toList();
print(replies);
await channel.sink.close();
await server.close();
}
Output:
Serving at ws://localhost:50662
[echo: one, echo: two]
Since shelf_web_socket 3.0, the callback must take two parameters. Old code written as webSocketHandler((ws) { ... }) no longer compiles; add a second parameter: webSocketHandler((ws, _) { ... }).
The webSocketHandler() options:
| Parameter | Purpose |
|---|---|
protocols |
subprotocols the server supports, in order of preference |
allowedOrigins |
if set, reject handshakes whose Origin header isn't in the list (403) |
pingInterval |
send a ping this often and close the connection if no pong arrives |
A chat room: routing, broadcasting and JSON
A real server usually has WebSockets on one path and normal HTTP routes on others. With shelf_router you call the handler returned by webSocketHandler() from inside a route, which also lets you read the request (query parameters, headers) first and reject it with a normal HTTP response.
WebSockets carry only strings and bytes, so applications define their own message format, most often JSON objects with a type field. This chat server keeps a map of connected clients, broadcasts every message to all of them, and uses pattern matching to dispatch on the message type:
import 'dart:convert';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class ChatRoom {
final _members = <WebSocketChannel, String>{};
void join(WebSocketChannel ws, String name) {
_members[ws] = name;
broadcast({'type': 'joined', 'name': name, 'online': _members.length});
ws.stream.listen(
(data) {
final Map<String, dynamic> msg;
try {
msg = jsonDecode(data as String) as Map<String, dynamic>;
} catch (_) {
ws.sink.add(jsonEncode({'type': 'error', 'error': 'invalid JSON'}));
return;
}
switch (msg) {
case {'type': 'say', 'text': String text}:
broadcast({'type': 'message', 'from': name, 'text': text});
case {'type': 'ping'}:
ws.sink.add(jsonEncode({'type': 'pong'}));
default:
ws.sink.add(jsonEncode({'type': 'error', 'error': 'unknown message'}));
}
},
onDone: () {
_members.remove(ws);
broadcast({'type': 'left', 'name': name, 'online': _members.length});
},
);
}
void broadcast(Map<String, Object?> msg) {
final encoded = jsonEncode(msg); // encode once, send to everyone
for (final ws in _members.keys) {
ws.sink.add(encoded);
}
}
}
Future<void> main() async {
final room = ChatRoom();
final router = Router()
..get('/health', (Request req) => Response.ok('ok'))
..get('/chat', (Request req) {
final name = req.url.queryParameters['name'];
if (name == null || name.isEmpty) {
return Response.badRequest(body: 'name is required');
}
return webSocketHandler((WebSocketChannel ws, _) => room.join(ws, name))(req);
});
final server = await shelf_io.serve(router.call, 'localhost', 0);
final base = 'ws://localhost:${server.port}/chat';
Future<WebSocketChannel> connect(String name) async {
final ch = WebSocketChannel.connect(Uri.parse('$base?name=$name'));
await ch.ready;
ch.stream.listen((m) => print('$name <- $m'));
return ch;
}
final alice = await connect('alice');
await Future.delayed(const Duration(milliseconds: 100));
final bob = await connect('bob');
await Future.delayed(const Duration(milliseconds: 100));
alice.sink.add(jsonEncode({'type': 'say', 'text': 'hi bob'}));
bob.sink.add('not json');
await Future.delayed(const Duration(milliseconds: 100));
await bob.sink.close();
await Future.delayed(const Duration(milliseconds: 100));
await alice.sink.close();
await server.close();
}
Output:
alice <- {"type":"joined","name":"alice","online":1}
alice <- {"type":"joined","name":"bob","online":2}
bob <- {"type":"joined","name":"bob","online":2}
alice <- {"type":"message","from":"alice","text":"hi bob"}
bob <- {"type":"message","from":"alice","text":"hi bob"}
bob <- {"type":"error","error":"invalid JSON"}
alice <- {"type":"left","name":"bob","online":1}
Points worth copying:
- Remove clients in
onDone. The stream completes when the client closes the connection or the connection drops. Forgetting to remove the channel there is the most common WebSocket memory leak. - Never trust incoming data. Bad JSON, or a binary frame where you expect text, must not crash the handler. An exception thrown inside a
listencallback is an uncaught asynchronous error, not something the client ever hears about. - Encode once when broadcasting.
jsonEncodethe message one time and send the same string to every client. - A single Dart isolate can hold thousands of idle WebSocket connections. If a server runs several isolates or several processes, each has its own
_membersmap, and broadcasting across them needs a shared channel such as Redis pub/sub (see Redis).
See JSON for turning such maps into typed classes.
Pushing server events and cleaning up
Often the server forwards events from some other source, such as a broadcast stream. Each connection subscribes to it, and that subscription must be cancelled when the client goes away:
import 'dart:async';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
// Shared source of events, e.g. price updates from elsewhere in the app.
// The timer runs only while at least one client is listening.
Timer? timer;
var price = 100;
late final StreamController<String> prices = StreamController.broadcast(
onListen: () => timer = Timer.periodic(
const Duration(milliseconds: 100),
(_) => prices.add('price ${price++}'),
),
onCancel: () => timer?.cancel(),
);
var activeSubscriptions = 0;
Future<void> main() async {
final server = await shelf_io.serve(
webSocketHandler((WebSocketChannel ws, _) {
activeSubscriptions++;
final sub = prices.stream.listen(ws.sink.add);
// Without this, the subscription (and ws) leak after the client leaves.
ws.stream.listen(null, onDone: () {
sub.cancel();
activeSubscriptions--;
});
}),
'localhost',
0,
);
final ch = WebSocketChannel.connect(Uri.parse('ws://localhost:${server.port}'));
await ch.ready;
print(await ch.stream.take(3).toList());
print('subscriptions while connected: $activeSubscriptions');
await ch.sink.close();
await Future.delayed(const Duration(milliseconds: 100));
print('subscriptions after close: $activeSubscriptions');
await server.close();
}
Output:
[price 100, price 101, price 102]
subscriptions while connected: 1
subscriptions after close: 0
The broadcast StreamController with onListen and onCancel starts the timer when the first client subscribes and stops it when the last one leaves. Plain asBroadcastStream() keeps its source running after the last listener cancels, which here keeps the program from exiting.
Errors, origins and plain HTTP requests
Connection failures surface from channel.ready (or from the stream if you don't await ready) as a WebSocketChannelException. Its inner field holds the underlying error:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
Future<void> main() async {
final handler = webSocketHandler(
(WebSocketChannel ws, _) => ws.sink.add('welcome'),
allowedOrigins: ['https://app.example.com'],
);
final server = await shelf_io.serve(handler, 'localhost', 0);
final url = 'ws://localhost:${server.port}';
// 1. A plain HTTP request to a WebSocket endpoint
final res = await http.get(Uri.parse('http://localhost:${server.port}'));
print('plain GET: ${res.statusCode}, ${res.body.contains('Only WebSocket')}');
// 2. Connecting to a server that isn't there
final nobody = WebSocketChannel.connect(Uri.parse('ws://localhost:1'));
try {
await nobody.ready;
} on WebSocketChannelException catch (e) {
print('no server: ${e.inner.runtimeType}');
}
// 3. Origin not on the allow list (dart:io lets us set any header)
final bad = IOWebSocketChannel.connect(url,
headers: {'origin': 'https://evil.example'});
try {
await bad.ready;
} on WebSocketChannelException catch (e) {
print('bad origin: ${e.message}');
}
// 4. Allowed origin
final good = IOWebSocketChannel.connect(url,
headers: {'origin': 'https://app.example.com'});
await good.ready;
print('good origin: ${await good.stream.first}');
await server.close(force: true);
exit(0);
}
Output:
plain GET: 404, true
no server: SocketException
bad origin: WebSocketException: Connection to 'http://localhost:50750#' was not upgraded to websocket, HTTP status code: 403
good origin: welcome
- A request without the upgrade headers gets
404with the text "Only WebSocket connections are supported." allowedOriginsrejects the handshake with403.
Why check Origin at all? Browsers don't apply CORS to WebSockets. Any web page can open a WebSocket to your server, and the browser sends the user's cookies with the handshake. If you authenticate WebSockets with cookies, a malicious page could act as the user ("cross-site WebSocket hijacking"). Checking Origin against your own sites, or authenticating with a token instead of cookies, prevents this. Non-browser clients can send any Origin they like, as the example shows, so Origin checks protect browser users but are not authentication.
Authentication and subprotocols
The browser WebSocket API can't set request headers, so Authorization: Bearer ... isn't available from web clients. The usual options:
- a token in the query string:
wss://api.example.com/ws?token=...(always usewss, and keep the token short-lived, because URLs end up in logs) - a session cookie, together with an
Origincheck - a first message
{"type":"auth","token":"..."}that the server requires before anything else
Check credentials before upgrading, so a bad client gets an HTTP error instead of an open connection. Subprotocols, sent in the Sec-WebSocket-Protocol header, let the client and server agree on a message format or version: the client lists what it supports, and the server picks one from its own protocols list:
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
const validTokens = {'t0k3n-alice': 'alice'};
Handler authenticatedSocket() {
return (Request req) {
final user = validTokens[req.url.queryParameters['token']];
if (user == null) {
return Response.unauthorized('bad token'); // rejected before upgrading
}
return webSocketHandler(
(WebSocketChannel ws, String? protocol) {
ws.sink.add('hello $user, protocol=$protocol');
ws.stream.listen((msg) {
if (msg == 'quit') {
ws.sink.close(4000, 'client asked to quit');
}
});
},
protocols: ['chat.v2', 'chat.v1'],
)(req);
};
}
Future<void> main() async {
final server = await shelf_io.serve(authenticatedSocket(), 'localhost', 0);
final base = 'ws://localhost:${server.port}/';
final anon = WebSocketChannel.connect(Uri.parse('$base?token=wrong'));
try {
await anon.ready;
} on WebSocketChannelException catch (e) {
print('rejected: ${e.message}');
}
final ch = WebSocketChannel.connect(
Uri.parse('$base?token=t0k3n-alice'),
protocols: ['chat.v1'],
);
await ch.ready;
print('negotiated protocol: ${ch.protocol}');
ch.stream.listen(
print,
onDone: () => print('closed: ${ch.closeCode} ${ch.closeReason}'),
);
ch.sink.add('quit');
await Future.delayed(const Duration(milliseconds: 200));
await server.close();
}
Output:
rejected: WebSocketException: Connection to 'http://localhost:50781/?token=wrong#' was not upgraded to websocket
negotiated protocol: chat.v1
hello alice, protocol=chat.v1
closed: 4000 client asked to quit
The client sees only that the upgrade failed, not the 401 body. If clients need to know why they were rejected (to refresh a token, say), accept the connection and then close it with an application code such as 4001.
Non-browser clients can send headers. With dart:io use WebSocket.connect(url, headers: {...}), or IOWebSocketChannel.connect(url, headers: {...}) from package:web_socket_channel/io.dart. For token formats see JWT and Authentication.
Reconnecting with backoff
Mobile networks drop, servers restart, and load balancers close idle connections. A client that must stay connected needs to reconnect on its own. Wait longer after each failure (exponential backoff), add random jitter so thousands of clients don't reconnect at the same moment after a server restart, and reset the delay after a successful connection:
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
/// Keeps a connection open, reconnecting with exponential backoff.
class ReconnectingSocket {
ReconnectingSocket(this.uri, {this.maxDelay = const Duration(seconds: 30)});
final Uri uri;
final Duration maxDelay;
final _messages = StreamController<dynamic>.broadcast();
final _random = Random();
WebSocketChannel? _channel;
var _attempt = 0;
var _stopped = false;
Stream<dynamic> get messages => _messages.stream;
Future<void> start() async {
while (!_stopped) {
final channel = WebSocketChannel.connect(uri);
try {
await channel.ready;
} on WebSocketChannelException catch (e) {
await _backoff('connect failed (${e.inner.runtimeType})');
continue;
}
_channel = channel;
_attempt = 0; // connected: reset the backoff
print('connected');
await channel.stream.forEach(_messages.add); // completes on close
_channel = null;
if (!_stopped) await _backoff('connection closed (${channel.closeCode})');
}
}
Future<void> _backoff(String why) async {
_attempt++;
// 250ms, 500ms, 1s, 2s ... capped, plus up to 20% random jitter
final base = min(250 * pow(2, _attempt - 1).toInt(), maxDelay.inMilliseconds);
final delay = base + _random.nextInt(base ~/ 5 + 1);
print('$why, retry #$_attempt in ~${base}ms');
await Future.delayed(Duration(milliseconds: delay));
}
void send(String message) => _channel?.sink.add(message);
Future<void> stop() async {
_stopped = true;
await _channel?.sink.close();
await _messages.close();
}
}
Future<void> main() async {
// Reserve a free port, then free it so the server can start there later.
final probe = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = probe.port;
await probe.close();
final socket = ReconnectingSocket(Uri.parse('ws://127.0.0.1:$port'));
socket.messages.listen((m) => print('got: $m'));
unawaited(socket.start());
// The server comes up late, and kicks every client after one message.
await Future.delayed(const Duration(seconds: 5));
var connection = 0;
final server = await shelf_io.serve(
webSocketHandler((WebSocketChannel ws, _) {
ws.sink.add('hello #${++connection}');
ws.sink.close(4001, 'server restarting');
}),
InternetAddress.loopbackIPv4,
port,
);
await Future.delayed(const Duration(milliseconds: 1200));
await socket.stop();
await server.close(force: true);
}
Output:
connect failed (SocketException), retry #1 in ~250ms
connect failed (SocketException), retry #2 in ~500ms
connected
got: hello #1
connection closed (4001), retry #1 in ~250ms
connected
got: hello #2
connection closed (4001), retry #1 in ~250ms
connected
got: hello #3
connection closed (4001), retry #1 in ~250ms
(On Windows a refused connection to localhost takes about two seconds to fail, which is why only two attempts happen in the five seconds before the server starts.)
channel.stream.forEach completes when the connection closes, which is a convenient way to "wait until disconnected". After reconnecting, the client usually has to re-send its subscriptions or ask for the messages it missed, because the server doesn't remember a closed connection. For stopping work on a timer see also Cancellation and timeouts.
Detecting dead connections with pings
If a client disappears without closing the TCP connection (a phone loses its network, a laptop goes to sleep), the server doesn't notice: no close frame arrives and the socket looks open for a long time. WebSocket ping and pong control frames solve this. One side sends a ping, the other must answer with a pong automatically.
In dart:io set WebSocket.pingInterval. In Shelf pass pingInterval: to webSocketHandler(). If no pong arrives before the next ping is due, the connection is closed with code 1001. This example fakes a client that completes the handshake over a raw socket and then never answers:
import 'dart:io';
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen((req) async {
final ws = await WebSocketTransformer.upgrade(req);
ws.pingInterval = const Duration(milliseconds: 500);
final started = DateTime.now();
ws.listen(null, onDone: () {
final ms = DateTime.now().difference(started).inMilliseconds;
print('server: client gone after ~${(ms / 100).round() * 100}ms, '
'closeCode=${ws.closeCode}');
});
});
// A "client" that completes the handshake and then never answers pings,
// like a phone that lost its network without sending a TCP FIN.
final socket = await Socket.connect(InternetAddress.loopbackIPv4, server.port);
socket.write('GET / HTTP/1.1\r\n'
'Host: localhost\r\n'
'Upgrade: websocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n'
'Sec-WebSocket-Version: 13\r\n\r\n');
socket.listen((data) {}); // read and ignore everything, including pings
await Future.delayed(const Duration(seconds: 2));
socket.destroy();
await server.close();
}
Output:
server: client gone after ~1000ms, closeCode=1001
The first ping goes out after 500 ms; with no pong by the next tick, the server gives up. In production an interval of 20-30 seconds is typical. That also keeps proxies and load balancers, which often drop connections idle for 60 seconds, from closing healthy connections. Browsers answer pings automatically but don't expose them to JavaScript, so browser clients that want to detect a dead server send application-level {"type":"ping"} messages, as the chat example supports.
The package:web_socket API
package:web_socket is a small, newer API from the Dart team that web_socket_channel 3.x is built on. Instead of a stream of dynamic, it gives a stream of a sealed WebSocketEvent type, so a switch handles every case and the close code arrives as an event:
import 'dart:typed_data';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket/web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
Future<void> main() async {
final server = await shelf_io.serve(
webSocketHandler((WebSocketChannel ws, _) {
ws.stream.listen((m) {
ws.sink.add(m); // echo text as text and bytes as bytes
if (m == 'bye') ws.sink.close(4002, 'see you');
});
}),
'localhost',
0,
);
final socket =
await WebSocket.connect(Uri.parse('ws://localhost:${server.port}'));
socket.sendText('hello');
socket.sendBytes(Uint8List.fromList([0xCA, 0xFE]));
socket.sendText('bye');
await for (final event in socket.events) {
switch (event) {
case TextDataReceived(:final text):
print('text: $text');
case BinaryDataReceived(:final data):
print('bytes: $data');
case CloseReceived(:final code, :final reason):
print('closed by server: $code $reason');
}
}
try {
socket.sendText('too late');
} on WebSocketConnectionClosed catch (e) {
print(e);
}
await server.close();
}
Output:
text: hello
bytes: [202, 254]
text: bye
closed by server: 4002 see you
WebSocketConnectionClosed: Connection Closed
Use sendText and sendBytes instead of guessing the frame type from the object. Sending after the connection closed throws WebSocketConnectionClosed. Flutter apps can plug in platform implementations of the same interface, such as cupertino_http's WebSocket on iOS and macOS, without changing the code that uses it.
WebSockets in the browser
The same WebSocketChannel.connect() call works when Dart is compiled to JavaScript or WebAssembly, including Flutter web. Use ws:// for pages served over http:// and wss:// for https:// pages; browsers block ws:// from an https:// page as mixed content. Building the URL from Uri.base keeps the page and socket on the same host:
import 'package:web/web.dart' as web;
import 'package:web_socket_channel/web_socket_channel.dart';
Future<void> main() async {
final out = web.document.querySelector('#out') as web.HTMLPreElement;
void log(String s) {
print(s);
out.textContent = '${out.textContent}$s\n';
}
// Same origin as the page: ws:// for http:// pages, wss:// for https:// pages
final page = Uri.base;
final uri = page.replace(
scheme: page.scheme == 'https' ? 'wss' : 'ws',
path: '/ws',
queryParameters: {'token': 't0k3n-alice'}, // browsers can't set headers
);
final channel = WebSocketChannel.connect(uri);
try {
await channel.ready;
} on WebSocketChannelException catch (e) {
log('connect failed: $e');
return;
}
channel.stream.listen(
(m) => log('got: $m'),
onDone: () => log('closed: ${channel.closeCode}'),
);
channel.sink.add('hello from the browser');
}
A small server that serves the page, the compiled main.js and the /ws endpoint:
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
Future<void> main() async {
final webDir = Platform.script.resolve('../web/').toFilePath();
final router = Router()
..get('/', (Request r) => Response.ok(
'<!doctype html><pre id="out"></pre><script src="main.js"></script>',
headers: {'content-type': 'text/html'}))
..get('/main.js', (Request r) => Response.ok(
File('${webDir}main.js').readAsStringSync(),
headers: {'content-type': 'text/javascript'}))
..get('/ws', (Request req) {
if (req.url.queryParameters['token'] != 't0k3n-alice') {
return Response.unauthorized('bad token');
}
return webSocketHandler((WebSocketChannel ws, _) {
ws.stream.listen((m) {
print('server got: $m (origin ${req.headers['origin']})');
ws.sink.add('echo: $m');
ws.sink.close(1000, 'done');
});
})(req);
});
final server = await shelf_io.serve(router.call, 'localhost', 0);
print('Open http://localhost:${server.port}/');
}
After dart compile js web/main.dart -o web/main.js and opening the page in Chrome, the page shows:
got: echo: hello from the browser
closed: 1000
and the server prints:
Open http://localhost:64422/
server got: hello from the browser (origin http://localhost:64422)
The browser added the Origin header itself. Browser clients can't add custom headers, can't see the HTTP status of a failed handshake (it's just "connect failed"), and can't send pings.
For wss:// in production, terminate TLS in a reverse proxy such as nginx or Caddy, or bind the Dart server with HttpServer.bindSecure (see TLS and HTTPS). Proxies must forward the Upgrade and Connection headers and allow long-lived connections; nginx, for example, needs proxy_http_version 1.1, proxy_set_header Upgrade $http_upgrade, proxy_set_header Connection "upgrade" and a large proxy_read_timeout.
Common mistakes
| Mistake | Fix |
|---|---|
webSocketHandler((ws) { ... }) doesn't compile |
shelf_web_socket 3.x needs two parameters: (ws, protocol) or (ws, _) |
| Clients are never removed from the broadcast list | remove them, and cancel their subscriptions, in the stream's onDone |
| Server crashes on a bad message | wrap jsonDecode and casts in try/catch, check is String before decoding |
ArgumentError when closing with 1001 or 1011 |
web_socket_channel only sends 1000 or 3000-4999; use your own 4xxx codes |
Listening to channel.stream twice |
it's a single-subscription stream; listen once and fan out yourself, or use asBroadcastStream() |
| Errors only appear later, on the stream | await channel.ready right after connect to get handshake errors in one place |
| Silent connections stay open forever | set pingInterval on the server |
| Middleware breaks WebSockets | Shelf takes over the socket by throwing HijackException; error-handling middleware must rethrow it (see HTTP middleware) |
| Cookie-authenticated socket opened from another site | check Origin (allowedOrigins) or authenticate with a token |
| Works locally, drops after 60 s in production | the proxy closes idle connections: send pings and raise the proxy's read timeout |
ws:// blocked from an https:// page |
use wss:// |
When the server shuts down, close each open socket with code 1001 or a 4xxx "restarting" code so clients reconnect quickly; see Signals and graceful shutdown.
Summary
| Task | How |
|---|---|
Upgrade a dart:io request |
await WebSocketTransformer.upgrade(req) |
| WebSocket route in Shelf | webSocketHandler((WebSocketChannel ws, String? protocol) { ... }) |
| Connect from any platform | WebSocketChannel.connect(uri), then await channel.ready |
| Send text / binary | sink.add('text') / sink.add(bytes) |
| Receive | channel.stream.listen(...), check is String |
| Close with a reason | sink.close(4000, 'reason') |
| Notice the client left | onDone of the stream, then read closeCode |
| Restrict browser origins | allowedOrigins: ['https://app.example.com'] |
| Choose a message format | protocols: on both sides, read channel.protocol |
| Detect dead peers | pingInterval: Duration(seconds: 25) |
| Typed client events | package:web_socket, switch on socket.events |
| Stay connected | reconnect loop with exponential backoff and jitter |
For plain HTTP clients see HTTP Request, and for building HTTP servers with Shelf see REST APIs.