connect method
Opens the socket and completes the authentication handshake.
The hub sends a challenge the instant the socket opens and honours nothing
else until it is answered, so this does not return until the hub has said
authOk — a caller that gets a future back can assume the connection is
usable. Throws HubConnectionException if the hub refuses.
Implementation
Future<void> connect({
Duration timeout = const Duration(seconds: 10),
required String nodeUId,
}) async {
if (_channel != null) return;
final channel = WebSocketChannel.connect(hubUri);
await channel.ready.timeout(timeout);
_channel = channel;
_nodeUId = nodeUId;
final authenticated = _authenticated = Completer<void>();
_subscription = channel.stream.listen(
_onData,
onDone: _onClosed,
onError: (Object e) {
logger.warning('WebSocket error on $hubUri: $e');
_onClosed();
},
);
// The handshake shares the connect timeout: a hub that accepts the socket
// and then says nothing is no more usable than one that never accepted it.
await authenticated.future.timeout(
timeout,
onTimeout: () {
unawaited(close());
throw const HubConnectionException(
null,
'hub did not complete the authentication handshake',
);
},
);
logger.fine('Connected to hub at $hubUri as $nodeUId (epoch $_epoch)');
}