resilient_ws: Reliable Dart WebSocket & SSE Clients
ملخص
Pixel shares resilient_ws, a Dart and Flutter package for WebSocket and Server-Sent Events clients built to handle unstable mobile networks. It includes exponential backoff with jitter, fresh tokens for each connection, heartbeat checks, and a bounded offline message buffer, helping developers build more dependable realtime features across platforms.
DEV Community
resilient_ws: WebSocket and SSE clients for Dart that survive bad networks
Opening a WebSocket is one line of code. Keeping it open on a phone is the hard part. The user walks into a lift, the phone switches from Wi-Fi to mobile data, the app goes to the background, the access token expires. The socket dies, sometimes with an error and sometimes without a word. So every realtime feature ends up with the same code around the socket: reconnect, but not in a tight loop. Get a fresh token before reconnecting, because the old one may have expired. Notice a connection that is dead but still looks open. Re-subscribe to the topics. Do something sensible with messages sent while offline. And stop for good when the server says "you are not allowed", instead of retrying forever. resilient_ws packages that code. It has two realtime clients for Dart and Flutter that keep working on bad mobile networks: a WebSocket client and a Server-Sent Events client. Both reconnect on their own, fetch a fresh token for every connection, and stop cleanly when told to. Both work on every platform, including the web. What it does ResilientWebSocket States. connecting, open, reconnecting and closed, available as a stream and as a getter. Backoff. Exponential backoff with jitter and a cap: 1 s doubling to 30 s by default. The backoff resets only after a connection has stayed up for stableAfter (10 s by default), so a server that accepts and then drops connections does not get hammered. Fresh tokens. The token provider runs before every connection attempt. There are three ways to send the token: an HTTP header (dart:io only), a query parameter, or a first message. Heartbeat. An application-level ping. If no frame arrives within timeout of a ping, the client reconnects. Any inbound frame counts as proof of life, and pongs are not passed on to messages. Outbox. A bounded buffer for messages sent while disconnected, with a dropOldest or dropNewest overflow policy. Buffered messages are flushed in order after a reconnect. Subscriptions. Topic subscriptions are re-sent after every reconnect. The subscribe and unsubscribe frames come from a pluggable SubscriptionCodec. Typed messages. Messages go through a pluggable MessageCodec, with JsonMessageCodec included. Permanent close codes. Close codes that mean "stop" (1008, 4401 and 4403 by default, configurable) end the client instead of starting a retry loop. Network awareness. An optional Stream of network availability pauses reconnects while offline and reconnects at once when the network returns. Clean close. close() sends a close frame, cancels every timer, and never triggers a reconnect. SseClient The parser follows the WHATWG HTML "Server-sent events" section: the event, data (multi-line), id and retry fields, comments and heartbeats, a leading BOM, and CRLF, CR and LF line endings, including a CRLF split across chunks. An event is dispatched only on a blank line. The client reconnects automatically, sends Last-Event-ID, and honours the server's retry: field. Consecutive failures double the wait, up to maxRetry. The token provider runs before every request. HTTP 204 stops the client, as the spec says. By default 4xx statuses stop it too, while 5xx, 408 and 429 are retried, and both rules are configurable. An optional idleTimeout reconnects when a connection goes silent, and the http.Client can be injected. How to use it Add it from GitHub: dependencies:
resilient_ws:
git: https://github.com/AbdeldjalilChougui/resilient_ws
A typed WebSocket client: import 'package:resilient_ws/resilient_ws.dart';
class Tick {
Tick(this.topic, this.value);
factory Tick.fromJson(Object? json) {
final map = json! as Map;
return Tick(map['topic']! as String, map['value']! as num);
}
final String topic;
final num value;
Map toJson() => {'topic': topic, 'value': value};
}
Future readAccessToken() async => 'token'; // your auth layer
Future main() async {
final ws = ResilientWebSocket(
url: Uri.parse('wss://...

Powered by Readybot.io