connect method
Connect
Implementation
@override
Future<MqttConnectionStatus?> connect(String server, int port) {
final completer = Completer<MqttConnectionStatus?>();
MqttLogger.log('MqttWsConnection::connectAuto - entered');
// Add the port if present
Uri uri;
try {
uri = Uri.parse(server);
} on Exception {
final message = 'MqttWsConnection::The URI supplied for the WS '
'connection is not valid - $server';
throw MqttNoConnectionException(message);
}
if (uri.scheme != 'ws' && uri.scheme != 'wss') {
final message = 'MqttWsConnection::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(
'MqttWsConnection:: WS URL is $uriString, protocols are $protocols');
HttpClient? httpClient;
if (onBadCertificate != null) {
httpClient = HttpClient()
..badCertificateCallback = (cert, host, port) {
return onBadCertificate!(cert);
};
}
try {
// Connect and save the socket.
WebSocket.connect(uriString,
protocols: protocols.isNotEmpty ? protocols : null,
customClient: httpClient)
.then((dynamic socket) {
client = socket;
_startListening();
completer.complete();
}).catchError((dynamic e) {
onError(e);
completer.completeError(e);
});
} on Exception {
final message = 'MqttWsConnection::The connection to the message broker '
'{$uriString} could not be made.';
throw MqttNoConnectionException(message);
}
return completer.future;
}