connect method
Connect
Implementation
@override
Future<MqttConnectionStatus?> connect(String server, int port) {
final completer = Completer<MqttConnectionStatus?>();
// Add the port if present
Uri uri;
try {
uri = Uri.parse(server);
} on Exception {
final message =
'MqttBrowserWsConnection::connect - The URI supplied for the WS '
'connection is not valid - $server';
throw MqttNoConnectionException(message);
}
if (uri.scheme != 'ws' && uri.scheme != 'wss') {
final message =
'MqttBrowserWsConnection::connect - The URI supplied for the WS has '
'an incorrect scheme - $server';
throw MqttNoConnectionException(message);
}
uri = uri.replace(port: port);
final uriString = uri.toString();
MqttLogger.log('MqttBrowserWsConnection::connect - WS URL is $uriString');
try {
// Connect and save the socket.
client = WebSocket(uriString, protocols.map((e) => e.toJS).toList().toJS);
wsClient.binaryType = 'arraybuffer';
StreamSubscription<Event>? openEvents;
StreamSubscription<CloseEvent>? closeEvents;
StreamSubscription<Event>? errorEvents;
openEvents = wsClient.onOpen.listen((e) {
MqttLogger.log('MqttBrowserWsConnection::connect - websocket is open');
openEvents?.cancel();
closeEvents?.cancel();
errorEvents?.cancel();
_startListening();
return completer.complete();
});
closeEvents = wsClient.onClose.listen((e) {
MqttLogger.log(
'MqttBrowserWsConnection::connect - websocket is closed');
openEvents?.cancel();
closeEvents?.cancel();
errorEvents?.cancel();
return completer.complete(MqttConnectionStatus());
});
errorEvents = wsClient.onError.listen((e) {
MqttLogger.log(
'MqttBrowserWsConnection::connect - websocket has errored');
openEvents?.cancel();
closeEvents?.cancel();
errorEvents?.cancel();
return completer.complete(MqttConnectionStatus());
});
} on Exception {
final message =
'MqttBrowserWsConnection::connect - The connection to the message broker '
'{$uriString} could not be made.';
throw MqttNoConnectionException(message);
}
MqttLogger.log('MqttBrowserWsConnection::connect - connection is waiting');
return completer.future;
}