connect method
Establishes a WebSocket connection
Implementation
@override
Future<void> connect() async {
if (_currentState == WebSocketState.connecting ||
_currentState == WebSocketState.connected) {
return;
}
_updateState(WebSocketState.connecting);
try {
final uri = Uri.parse(_config.url);
// Set up connection timeout
_connectionTimeoutTimer = Timer(_config.connectionTimeout, () {
if (_currentState == WebSocketState.connecting) {
_handleError(
TimeoutException('Connection timeout', _config.connectionTimeout),
);
}
});
_channel = connectChannel(uri, _config);
// Listen to the channel stream
_channelSubscription = _channel!.stream.listen(
_handleMessage,
onError: _handleError,
onDone: _handleDone,
);
// Wait for connection to be established
await _channel!.ready;
_connectionTimeoutTimer?.cancel();
_updateState(WebSocketState.connected);
} catch (error) {
_connectionTimeoutTimer?.cancel();
_updateState(WebSocketState.error);
_errorController.add(error);
rethrow;
}
}