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");

  Map<String, dynamic> headers = {};

  if (_accessTokenFactory != null) {
    final token = await _accessTokenFactory!();
    if (!isStringEmpty(token)) {
      headers['Authorization'] = 'Bearer $token';
    }
  }

  var websocketCompleter = Completer();
  var opened = false;
  url = url!.replaceFirst('http', 'ws');
  _logger?.finest("WebSocket try connecting to '$url'.");

  try {
    final webSocket = await WebSocket.connect(url, headers: headers);
    _webSocket = IOWebSocketChannel(webSocket);
    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.");
          }
        }
      },
    );
  } catch (e) {
    if (!websocketCompleter.isCompleted) {
      websocketCompleter.completeError(e);
    }
    _logger?.severe("WebSocket connection to '$url' failed: $e");
  }

  return websocketCompleter.future;
}