Skip to content
Back to archipelago.banuacoder.com

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 ​

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:

bash
archipelago generate websocket_sdk

The prompts are:

  • appName: your app name, for example MyApp
  • websocketLibrary: dart (raw dart:io, default) or phoenix
  • isForMonorepo: leave this as true

Or use a config file:

json
{
  "appName": "MyApp",
  "websocketLibrary": "dart",
  "isForMonorepo": true
}
bash
archipelago generate websocket_sdk --config ws_config.json

Only 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 ​

text
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 ​

LibraryUse When
dartStandard WebSocket servers and custom protocols
phoenixElixir 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:

dart
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:

dart
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) ​

dart
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 ​

CustomizationWhere to Change
Auth headersThe headers argument of connect
Ping and reconnectWebSocketConfig
Message handlingA WebSocketInterceptor
Several connectionsRegister more clients with @Named keys

Next Steps ​