Skip to content

Setting Up the WebSocket SDK

What you'll learn

  • Generating the WebSocket SDK with dart:io or Phoenix channel support
  • Understanding the WebSocket client abstraction layer
  • Connecting to a WebSocket server with automatic reconnection
  • Choosing between raw dart:io and Phoenix channels

Prerequisites

Step 1: Generate the WebSocket SDK

bash
archipelago generate websocket_sdk

You will be prompted for:

  • appNameMyApp (must match your monorepo app name)
  • websocketLibrarydart (raw dart:io) or phoenix (Phoenix channels)
  • isForMonorepotrue

Or use a config file:

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

Step 2: Understand the Generated Structure

infrastructure/
└── websocket_sdk/
    └── lib/src/
        ├── websocket_sdk.dart            # SDK entry point
        ├── client/
        │   ├── websocket_client.dart     # Abstract client contract
        │   └── dart_websocket_client.dart # dart:io implementation
        │   # OR
        │   └── phoenix_websocket_client.dart # Phoenix implementation
        ├── config/
        │   └── websocket_config.dart     # Connection configuration
        ├── di/                           # DI registration
        └── models/
            └── websocket_message.dart    # Message model

Step 3: dart:io vs Phoenix

LibraryUse When
dartStandard WebSocket servers, custom protocols
phoenixElixir/Phoenix backends with channel support

The Phoenix option includes channel joining, topic-based messaging, and presence tracking out of the box.

Step 4: Connect to a Server

dart
import 'package:websocket_sdk/websocket_sdk.dart';

final client = GetIt.I<WebSocketClient>();

// Connect
await client.connect(WebSocketConfig(
  url: 'wss://api.myapp.com/ws',
  reconnectInterval: Duration(seconds: 5),
  maxReconnectAttempts: 10,
));

// Listen for messages
client.messages.listen((message) {
  print('Received: ${message.data}');
});

// Send a message
client.send(WebSocketMessage(
  event: 'chat:message',
  data: {'text': 'Hello!'},
));

Step 5: Automatic Reconnection

The generated client handles disconnections automatically:

dart
client.connectionState.listen((state) {
  switch (state) {
    case ConnectionState.connected:
      print('Connected');
    case ConnectionState.reconnecting:
      print('Reconnecting...');
    case ConnectionState.disconnected:
      print('Disconnected');
  }
});

Step 6: Phoenix Channels (if selected)

With the phoenix option, you get channel-based messaging:

dart
final channel = await client.joinChannel('room:lobby');

channel.on('new_message', (payload) {
  print('New message: $payload');
});

channel.push('send_message', {'body': 'Hello!'});

Common Customizations

CustomizationWhere to Change
Auth headerswebsocket_config.dart — add token headers
Custom serializationmodels/websocket_message.dart
Reconnection strategyclient/ — adjust backoff logic
Multiple connectionsCreate multiple client instances via DI
Heartbeat intervalwebsocket_config.dart — ping/pong settings

Next Steps

Built by Banua Coder