Future initWebsocket([bool reconnect = true ])

Source

initWebsocket([bool reconnect = true]) async {
  if (_closed) return;

  reconnectWSCount++;
  if (reconnectWSCount > 10) {
    // if reconnected ws for more than 10 times, do a clean reconnct
    connDelay();
    return;
  }

  try {
    String wsUrl = '$_wsUpdateUri&auth=${_nonce.hashSalt(
        salts[0])}&format=$format';
    if (tokenHash != null) {
      wsUrl = '$wsUrl$tokenHash';
    }

    var socket = await HttpHelper.connectToWebSocket(wsUrl,
            useStandardWebSocket: useStandardWebSocket);

    _wsConnection = new WebSocketConnection(
        socket,
        clientLink: this,
        enableTimeout: true,
        enableAck: enableAck,
        useCodec: DsCodec.getCodec(format)
    );

    logger.info(formatLogMessage("Connected"));
    if (!_onConnectedCompleter.isCompleted) {
      _onConnectedCompleter.complete();
    }

    // Reset delays, we've successfully connected.
    _connDelay = 0;
    _wsDelay = 0;

    if (responder != null) {
      responder.connection = _wsConnection.responderChannel;
    }

    if (requester != null) {
      _wsConnection.onRequesterReady.then((channel) {
        requester.connection = channel;
        if (!_onRequesterReadyCompleter.isCompleted) {
          _onRequesterReadyCompleter.complete(requester);
        }
      });
    }

    _wsConnection.onDisconnected.then((connection) {
      initWebsocket();
    });
  } catch (error, stack) {
    logger.fine(
      formatLogMessage("Error while initializing WebSocket"),
      error,
      stack
    );
    if (error is WebSocketException && (
        error.message.contains('not upgraded to websocket') // error from dart
            || error.message.contains('(401)') // error from nodejs
    )) {
      connDelay();
    } else if (reconnect) {
      DsTimer.timerOnceAfter(
        initWebsocket,
        _wsDelay == 0 ? 20 : _wsDelay * 500
      );
      if (_wsDelay < 30) _wsDelay++;
    }
  }
}