connect method
Connect to the server
Returns true if the connection is successful, false otherwise
- Setup the Transport for the connection
- Start listening for incoming data
- Start the ping timer
- Perform the handshake
If the handshake is successful then incoming messages are handled by messages stream
If the handshake fails then the client will attempt to reconnect
Implementation
@override
Future<bool> connect() async {
if (_connectionStatusValue.isConnected) {
return true;
}
if (_handshaking) {
// already under connection
return _handshakeCompleter!.future;
}
try {
final connector = _WebSocketConnector(url);
_transport = Transport.create(connector);
_updateConnectionStatus(
_connectionStatusValue.isDisconnected
? ConnectionStatus.connecting
: ConnectionStatus.reconnecting,
);
_transport!.incoming.listen(
_handleIncomingData,
onError: (dynamic error, _) {
_handleTransportError(error);
},
);
final connected = await _performHandshake();
if (connected) {
_startPingTimer();
_updateConnectionStatus(ConnectionStatus.connected);
for (final plugin in plugins) {
plugin.onConnected();
}
}
return connected;
} catch (e) {
_updateConnectionStatus(ConnectionStatus.error);
return false;
}
}