connect method

  1. @override
Future<void> connect(
  1. String? url,
  2. TransferFormat transferFormat
)
override

Implementation

@override
Future<void> connect(String? url, TransferFormat transferFormat) async {
  assert(url != null);

  _logger?.finest("(WebSockets transport) Connecting");

  if (_accessTokenFactory != null) {
    final token = await _accessTokenFactory!();
    if (!isStringEmpty(token)) {
      final encodedToken = Uri.encodeComponent(token);
      url = url! +
          (url.indexOf("?") < 0 ? "?" : "&") +
          "access_token=$encodedToken";
    }
  }

  var websocketCompleter = Completer();
  var opened = false;
  url = url!.replaceFirst('http', 'ws');
  _logger?.finest("WebSocket try connecting to '$url'.");
  _webSocket = WebSocketChannel.connect(Uri.parse(url));
  opened = true;
  if (!websocketCompleter.isCompleted) websocketCompleter.complete();
  _logger?.info("WebSocket connected to '$url'.");
  _webSocketListenSub = _webSocket!.stream.listen(
    // onData
    (Object? message) {
      if (_logMessageContent && message is String) {
        _logger?.finest(
            "(WebSockets transport) data received. message ${getDataDetail(message, _logMessageContent)}.");
      } else {
        _logger?.finest("(WebSockets transport) data received.");
      }
      if (onReceive != null) {
        try {
          onReceive!(message);
        } catch (error) {
          _logger?.severe(
              "(WebSockets transport) error calling onReceive, error: $error");
          _close();
        }
      }
    },

    // onError
    onError: (Object? error) {
      var e = error != null ? error : "Unknown websocket error";
      if (!websocketCompleter.isCompleted) {
        websocketCompleter.completeError(e);
      }
    },

    // onDone
    onDone: () {
      // Don't call close handler if connection was never established
      // We'll reject the connect call instead
      if (opened) {
        if (onClose != null) {
          onClose!();
        }
      } else {
        if (!websocketCompleter.isCompleted) {
          websocketCompleter
              .completeError("There was an error with the transport.");
        }
      }
    },
  );

  return websocketCompleter.future;
}