openStreamingConnection method
Open a streaming connection to the server.
Implementation
Future<void> openStreamingConnection({
bool disconnectOnLostInternetConnection = true,
}) async {
if (_webSocket != null) return;
if (disconnectOnLostInternetConnection) {
assert(
_connectivityMonitor != null,
'To enable automatic disconnect on lost internet connection, you need to set the connectivityMonitor propery.',
);
}
_disconnectOnLostInternetConnection = disconnectOnLostInternetConnection;
try {
// Connect to the server.
_firstMessageReceived = false;
var host = await websocketHost;
_webSocket = WebSocketChannel.connect(Uri.parse(host));
// We are sending the ping message to the server, so that we are
// guaranteed to get a first message in return. This will verify that we
// have an open connection to the server.
await _sendControlCommandToStream('ping');
unawaited(_listenToWebSocketStream());
// Time out and close the connection if we haven't got a pong response
// within the timeout period.
_connectionTimer = Timer(streamingConnectionTimeout, () async {
if (!_firstMessageReceived) {
await _webSocket?.sink.close();
_webSocket = null;
_cancelConnectionTimer();
_notifyWebSocketConnectionStatusListeners();
}
});
} catch (e) {
_webSocket = null;
_cancelConnectionTimer();
rethrow;
}
// If everything is going according to plan, we are now connected to the
// server.
_notifyWebSocketConnectionStatusListeners();
}