maybeUpgrade method

void maybeUpgrade(
  1. dynamic transport
)

Upgrades socket to the given transport

Implementation

void maybeUpgrade(transport) {
  upgrading = true;
  var cleanupFn = {};
  // set transport upgrade timer
  upgradeTimeoutTimer =
      Timer(Duration(milliseconds: server.upgradeTimeout), () {
    cleanupFn['cleanup']();
    if ('open' == transport.readyState) {
      transport.close();
    }
  });

  // we force a polling cycle to ensure a fast upgrade
  check() {
    if ('polling' == this.transport.name && this.transport.writable == true) {
      this.transport.send([
        {'type': 'noop'}
      ]);
    }
  }

  onPacket(packet) {
    if ('ping' == packet['type'] && 'probe' == packet['data']) {
      transport.send([
        {'type': 'pong', 'data': 'probe'}
      ]);
      emit('upgrading', transport);
      if (checkIntervalTimer != null) {
        checkIntervalTimer!.cancel();
      }
      checkIntervalTimer =
          Timer.periodic(Duration(milliseconds: 100), (_) => check());
    } else if ('upgrade' == packet['type'] && readyState != 'closed') {
      cleanupFn['cleanup']();
      this.transport.discard();
      upgraded = true;
      clearTransport();
      setTransport(transport);
      emit('upgrade', transport);
      setPingTimeout();
      flush();
      if (readyState == 'closing') {
        transport.close(() {
          this.onClose('forced close');
        });
      }
    } else {
      cleanupFn['cleanup']();
      transport.close();
    }
  }

  onError(err) {
    cleanupFn['cleanup']();
    transport.close();
    transport = null;
  }

  onTransportClose(_) {
    onError('transport closed');
  }

  onClose(_) {
    onError('socket closed');
  }

  cleanup() {
    upgrading = false;
    checkIntervalTimer?.cancel();
    checkIntervalTimer = null;

    upgradeTimeoutTimer?.cancel();
    upgradeTimeoutTimer = null;

    transport.off('packet', onPacket);
    transport.off('close', onTransportClose);
    transport.off('error', onError);
    off('close', onClose);
  }

  cleanupFn['cleanup'] = cleanup; // define it later
  transport.on('packet', onPacket);
  transport.once('close', onTransportClose);
  transport.once('error', onError);

  once('close', onClose);
}