connect method
Attempts to make a WebSocket connection to the Phoenix backend.
If the attempt fails, retries will be triggered at intervals specified by retryAfterIntervalMS
Implementation
Future<PhoenixSocket?> connect() async {
if (_ws != null) {
_logger.warning(
'Calling connect() on already connected or connecting socket.');
return this;
}
_shouldReconnect = true;
if (_disposed) {
throw StateError('PhoenixSocket cannot connect after being disposed.');
}
_mountPoint = await _buildMountPoint(_endpoint, _options);
_logger.finest(() => 'Attempting to connect to $_mountPoint');
final completer = Completer<PhoenixSocket?>();
try {
_ws = _webSocketChannelFactory != null
? _webSocketChannelFactory!(_mountPoint)
: WebSocketChannel.connect(_mountPoint);
_ws!.stream
.where(_shouldPipeMessage)
.listen(_onSocketData, cancelOnError: true)
..onError(_onSocketError)
..onDone(_onSocketClosed);
} catch (error, stacktrace) {
_onSocketError(error, stacktrace);
}
_reconnectAttempts++;
_socketState = SocketState.connecting;
try {
_socketState = SocketState.connected;
_logger.finest('Waiting for initial heartbeat roundtrip');
if (await _sendHeartbeat(ignorePreviousHeartbeat: true)) {
_stateStreamController.add(PhoenixSocketOpenEvent());
_logger.info('Socket open');
completer.complete(this);
} else {
throw PhoenixException();
}
} catch (err, stackTrace) {
_logger.severe('Raised Exception', err, stackTrace);
_ws = null;
_socketState = SocketState.closed;
completer.complete(_delayedReconnect());
}
return completer.future;
}