Infrastructure SDKs
How to add a WebSocket client to a Flutter app
Free Reference for websocket_sdk: every variable, option and package it generates. Command: archipelago generate websocket_sdk
Generate the WebSocket SDK with dart:io or Phoenix, connect, send and listen, turn on reconnection, and use Phoenix channels.
What you'll learn
- Generating the WebSocket SDK with the dart:io or Phoenix backend
- Understanding the client abstraction
- Connecting, sending and listening
- Turning on reconnection for the dart:io client
- Using Phoenix channels
Prerequisites
- An existing Archipelago monorepo (see Monorepo Scaffolding)
The WebSocket SDK does not depend on the Network SDK.
Step 1: Generate the WebSocket SDK
Pick the library at project creation with isUsingWebSocket and websocketLibrary. To add it later, run:
archipelago generate websocket_sdkThe prompts are:
- appName: your app name, for example
MyApp - websocketLibrary:
dart(rawdart:io, default) orphoenix - isForMonorepo: leave this as
true
Or use a config file:
{
"appName": "MyApp",
"websocketLibrary": "dart",
"isForMonorepo": true
}archipelago generate websocket_sdk --config ws_config.jsonOnly one variant is wired. To switch, run the brick again with the other websocketLibrary. The hook unwires the old client in the same step. See Switch the client.
Step 2: Understand the Generated Structure
infrastructure/
├── websocket_sdk_api/ # Always generated
│ └── lib/src/
│ ├── client/websocket_client.dart
│ ├── exceptions/
│ ├── interceptor/
│ ├── message/
│ └── state/connection_state.dart
└── websocket_sdk_dart/ # Or websocket_sdk_phoenix
└── lib/src/
├── client/
├── config/
└── di/Features depend on websocket_sdk_api only.
Step 3: Check the Registration
The post-generation hook adds the variant to the app pubspec.yaml. It registers WebsocketSdkDartPackageModule or WebsocketSdkPhoenixPackageModule in lib/di/injector.dart. You write no registration code.
Step 4: Choose dart:io or Phoenix
| Library | Use When |
|---|---|
dart | Standard WebSocket servers and custom protocols |
phoenix | Elixir and Phoenix backends with channels |
The Phoenix variant uses phoenix_socket and adds a channel manager.
Step 5: Connect and Send
Take WebSocketClient by constructor:
client.stateStream.listen((state) => print('state: $state'));
client.messageStream.listen((message) {
print(message.dataAsMap ?? message.dataAsString);
});
await client.connect(
Uri.parse('wss://api.myapp.com/ws'),
headers: {'Authorization': 'Bearer $token'},
);
client.sendJson({'type': 'ping'});
client.sendText('hello');
await client.disconnect();ConnectionState has disconnected, connecting, connected, disconnecting and error. A WebSocketMessage has data, an optional type and the topic, event and ref fields for pub/sub systems. Call dispose() when you are done with the client.
Add interceptors with addInterceptor. app_debugger_websocket uses one to show traffic in the debug panel.
Step 6: Reconnection
Reconnection is off by default. The dart:io client reads WebSocketConfig:
const WebSocketConfig(
pingInterval: Duration(seconds: 30),
reconnectOnClose: true,
reconnectDelay: Duration(seconds: 5),
maxReconnectAttempts: 3,
compression: true,
)Provide your own config in a DI module to change it. The Phoenix variant handles reconnection through phoenix_socket. Watch stateStream and decide in your own code what to do on error.
Step 7: Phoenix Channels (Phoenix Variant)
final phoenix = client as PhoenixWebSocketClient;
final channel = await phoenix.joinChannel('room:lobby');
final withToken = await phoenix.joinChannelWithToken(
'room:private',
token: token,
);
phoenix.isChannelJoined('room:lobby');
await phoenix.leaveChannel('room:lobby');Import the Phoenix package only in the DI layer. Keep features on websocket_sdk_api when you can.
Common Customizations
| Customization | Where to Change |
|---|---|
| Auth headers | The headers argument of connect |
| Ping and reconnect | WebSocketConfig |
| Message handling | A WebSocketInterceptor |
| Several connections | Register more clients with @Named keys |
Next Steps
- Set up the Network SDK for HTTP alongside WebSocket
- Add the debugger panel to inspect traffic
- Configure Monitoring to track connection failures