connect method

Manager connect({
  1. dynamic callback,
  2. Map opts = emptyMap,
})

Implementation

Manager connect({callback, Map opts=emptyMap}) {
  _logger.fine('readyState $readyState');
  if (readyState.contains('open')) return this;

  _logger.fine('opening $uri');
  engine = engine_socket.Socket(uri, options);
  var socket = engine;
  readyState = 'opening';
  skipReconnect = false;

  // emit `open`
  var openSub = util.on(socket, 'open', (_) {
    onopen();
    if (callback != null) callback();
  });

  // emit `connect_error`
  var errorSub = util.on(socket, 'error', (data) {
    _logger.fine('connect_error');
    cleanup();
    readyState = 'closed';
    emitAll('connect_error', data);
    if (callback != null) {
      callback({'error': 'Connection error', 'data': data});
    } else {
      // Only do this if there is no fn to handle the error
      maybeReconnectOnOpen();
    }
  });

  // emit `connect_timeout`
  var timeout = this.timeout;
  if (timeout != null) {
    _logger.fine('connect attempt will timeout after $timeout');

    // set timer
    var timer = Timer(Duration(milliseconds: timeout.toInt()), () {
      _logger.fine('connect attempt timed out after $timeout');
      openSub.destroy();
      socket.close();
      socket.emit('error', 'timeout');
      emitAll('connect_timeout', timeout);
    });

    subs.add(Destroyable(() => timer.cancel()));
  }

  subs.add(openSub);
  subs.add(errorSub);

  return this;
}