WebSocket client for Cyaim.WebSocketServer with automatic endpoint discovery (Dart/Flutter)
- ✅ Automatic endpoint discovery from server
- ✅ Type-safe request and response
- ✅ Support for both JSON and MessagePack protocols
- ✅ Async/await support
- ✅ Error handling and timeout support
- ✅ Flutter/Dart compatible
Add to your pubspec.yaml:
dependencies:
cyaim_websocket_client:
path: ../cyaim-websocket-client-dartOr if published to pub.dev:
dependencies:
cyaim_websocket_client: ^1.0.0Then run:
dart pub getimport 'package:cyaim_websocket_client/cyaim_websocket_client.dart';
void main() async {
final factory = WebSocketClientFactory('http://localhost:5000', '/ws');
final client = factory.createClient();
await client.connect();
// Get forecasts
final forecasts = await client.sendRequest<List<Map<String, dynamic>>>(
'weatherforecast.get',
);
print('Forecasts: $forecasts');
// Get forecast by city
final forecast = await client.sendRequest<Map<String, dynamic>>(
'weatherforecast.getbycity',
{'city': 'Beijing'},
);
print('Forecast: $forecast');
await client.disconnect();
}import 'package:cyaim_websocket_client/cyaim_websocket_client.dart';
void main() async {
final options = WebSocketClientOptions();
options.protocol = SerializationProtocol.messagePack;
final factory = WebSocketClientFactory(
'http://localhost:5000',
'/ws',
options
);
final client = factory.createClient();
await client.connect();
final forecasts = await client.sendRequest<List<Map<String, dynamic>>>(
'weatherforecast.get',
);
print('Forecasts: $forecasts');
await client.disconnect();
}import 'package:cyaim_websocket_client/cyaim_websocket_client.dart';
void main() async {
final factory = WebSocketClientFactory('http://localhost:5000', '/ws');
// Get all available endpoints
final endpoints = await factory.getEndpoints();
for (final endpoint in endpoints) {
print('Endpoint: ${endpoint.target}');
print(' Controller: ${endpoint.controller}');
print(' Action: ${endpoint.action}');
print(' Method Path: ${endpoint.methodPath}');
}
final client = factory.createClient();
await client.connect();
// Use endpoint target
final result = await client.sendRequest<Map<String, dynamic>>(
endpoints.first.target,
);
await client.disconnect();
}Factory for creating WebSocket clients.
WebSocketClientFactory(
String serverBaseUrl,
String channel, [
WebSocketClientOptions? options
])serverBaseUrl: Server base URL (e.g., "http://localhost:5000")channel: WebSocket channel (default: "/ws")options: Optional client options
Future<List<WebSocketEndpointInfo>> getEndpoints(): Get all available endpoints from serverWebSocketClient createClient(): Create a WebSocket client instance
WebSocket client for connecting to server.
Future<void> connect(): Connect to serverFuture<T> sendRequest<T>(String target, [dynamic requestBody]): Send request and wait for responseFuture<void> disconnect(): Disconnect from server
Client configuration options.
SerializationProtocol protocol: Serialization protocol (default:SerializationProtocol.json)SerializationProtocol.json: JSON protocol (text messages)SerializationProtocol.messagePack: MessagePack protocol (binary messages)
bool validateAllMethods: Whether to validate all methods (default: false)bool lazyLoadEndpoints: Whether to lazy load endpoints (default: false)bool throwOnEndpointNotFound: Whether to throw exception if endpoint not found (default: true)
Enum for serialization protocols.
json: JSON protocol (text messages)messagePack: MessagePack protocol (binary messages)
The server must provide the following API endpoint:
Returns all available WebSocket endpoints.
Response format:
{
"success": true,
"data": [
{
"controller": "WeatherForecast",
"action": "Get",
"methodPath": "weatherforecast.get",
"methods": ["GET"],
"fullName": "WeatherForecast.Get",
"target": "weatherforecast.get"
}
],
"error": null
}All methods throw exceptions on error:
StateError: WebSocket is not connectedException: Request failed, timeout, or server errorFormatException: Invalid response format
Example:
try {
final result = await client.sendRequest<Map<String, dynamic>>('endpoint');
} catch (e) {
print('Error: $e');
}Requests timeout after 30 seconds by default. If a timeout occurs, an Exception with message "Request timeout" is thrown.
- Connection Management: You must call
connect()before sending requests - Protocol Selection: Choose JSON for easier debugging, MessagePack for better performance
- Type Safety: Use generic type parameter
TinsendRequest<T>()for type-safe responses - Error Handling: Always wrap requests in try-catch blocks
- Server Compatibility: Ensure server supports the selected protocol (JSON or MessagePack)
MIT License
Copyright © Cyaim Studio