connect method
Connect
Implementation
@override
Future<MqttConnectionStatus?> connect(String server, int port) {
final completer = Completer<MqttConnectionStatus?>();
MqttLogger.log('MqttServerWs2Connection::connect - entered');
Uri uri;
try {
uri = Uri.parse(server);
} on Exception catch (_, stack) {
final message =
'MqttWsConnection::The URI supplied for the WS2 connection '
'is not valid - $server';
Error.throwWithStackTrace(MqttNoConnectionException(message), stack);
}
if (uri.scheme != 'wss') {
final message =
'MqttWsConnection::The URI supplied for the WS2 has an '
'incorrect scheme - $server';
throw MqttNoConnectionException(message);
}
uri = uri.replace(port: port);
final uriString = uri.toString();
MqttLogger.log(
'MqttServerWs2Connection:: WS URL is $uriString, protocols are $protocols',
);
try {
SecureSocket.connect(
uri.host,
uri.port,
context: context,
onBadCertificate: onBadCertificate,
).then((Socket socket) {
MqttLogger.log('MqttServerWs2Connection::connect - securing socket');
_performWSHandshake(socket, uri)
.then((bool b) {
client = WebSocket.fromUpgradedSocket(
_DetachedSocket(
socket,
_subscription as StreamSubscription<Uint8List>?,
),
serverSide: false,
);
MqttLogger.log(
'MqttServerWs2Connection::connect - start listening',
);
_startListening();
completer.complete();
})
.catchError((dynamic e) {
onError(e);
completer.completeError(e);
});
});
} on SocketException catch (e, stack) {
final message =
'MqttServerWs2Connection::The connection to the message broker '
'{$server}:{$port} could not be made. Error is ${e.toString()}';
completer.completeError(e);
Error.throwWithStackTrace(MqttNoConnectionException(message), stack);
} on HandshakeException catch (e, stack) {
final message =
'MqttServerWs2Connection::Handshake exception to the message broker '
'{$server}:{$port}. Error is ${e.toString()}';
completer.completeError(e);
Error.throwWithStackTrace(MqttNoConnectionException(message), stack);
} on TlsException catch (e, stack) {
final message =
'MqttServerWs2Connection::TLS exception raised on secure connection. '
'Error is ${e.toString()}';
Error.throwWithStackTrace(MqttNoConnectionException(message), stack);
}
return completer.future;
}