it('should successfully listen to appripriate events on the connection', function () {
   DataRelay.init();
   expect(connection.listenerCount('connect')).to.equal(1);
   expect(connection.listenerCount('close')).to.equal(1);
   expect(connection.listenerCount('timeout')).to.equal(1);
   expect(connection.listenerCount('write')).to.equal(1);
   expect(connection.listenerCount('data')).to.equal(1);
 });
Example #2
0
  process.nextTick(function () {
    if (EventEmitter.listenerCount(process, 'uncaughtException') === 0) {
      process.on('uncaughtException', onerror);
    }

    if (EventEmitter.listenerCount(deamon, 'unexpectedExit') === 0) {
      deamon.on('unexpectedExit', onUnexpected);
    }
  });
Example #3
0
 // if the dest has an error, then stop piping into it.
 // however, don't suppress the throwing behavior for this.
 function onerror(er) {
   debug('onerror', er);
   unpipe();
   dest.removeListener('error', onerror);
   if (EE.listenerCount(dest, 'error') === 0)
     dest.emit('error', er);
 }
Example #4
0
function requestOCSP(self, hello, ctx, cb) {
  if (!hello.OCSPRequest || !self.server)
    return cb(null);

  if (!ctx)
    ctx = self.server._sharedCreds;
  if (ctx.context)
    ctx = ctx.context;

  if (listenerCount(self.server, 'OCSPRequest') === 0) {
    return cb(null);
  } else {
    self.server.emit('OCSPRequest',
                     ctx.getCertificate(),
                     ctx.getIssuer(),
                     onOCSP);
  }

  var once = false;
  function onOCSP(err, response) {
    if (once)
      return cb(new Error('TLS OCSP callback was called 2 times'));
    once = true;

    if (err)
      return cb(err);

    if (response)
      self._handle.setOCSPResponse(response);
    cb(null);
  }
}
function getSignalListenersCount(emitter, event) {
  if (emitter.listenerCount) { // Present in Node >= 4.0
    return emitter.listenerCount(event);
  } else {
    // deprecated in Node 4.0
    return EventEmitter.listenerCount(emitter, event);
  }
}
Example #6
0
 return function() {
   var state = src._readableState;
   debug('pipeOnDrain', state.awaitDrain);
   if (state.awaitDrain)
     state.awaitDrain--;
   if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
     state.flowing = true;
     flow(src);
   }
 };
	handleSocketError(error) {
		debug('handleSocketError: %j', error);
		this.closeReasonCode = WebSocketConnection.CLOSE_REASON_ABNORMAL;
		this.closeDescription = 'Socket Error: ' + error.syscall + ' ' + error.code;
		this.connected = false;
		this.state = STATE_CLOSED;
		this.fragmentationSize = 0;
		if (EventEmitter.listenerCount(this, 'error') > 0) {
			this.emit('error', error);
		}
		this.socket.destroy(error);
	}
'use strict';

require('../common');
const assert = require('assert');
const EventEmitter = require('events');

const emitter = new EventEmitter();
emitter.on('foo', () => {});
emitter.on('foo', () => {});
emitter.on('baz', () => {});
// Allow any type
emitter.on(123, () => {});

assert.strictEqual(EventEmitter.listenerCount(emitter, 'foo'), 2);
assert.strictEqual(emitter.listenerCount('foo'), 2);
assert.strictEqual(emitter.listenerCount('bar'), 0);
assert.strictEqual(emitter.listenerCount('baz'), 1);
assert.strictEqual(emitter.listenerCount(123), 1);
Example #9
0
 // don't leave dangling pipes when there are errors.
 function onerror(er) {
   cleanup();
   if (EE.listenerCount(this, 'error') === 0) {
     throw er; // Unhandled stream error in pipe.
   }
 }
Example #10
0
Domain.prototype._errorHandler = function _errorHandler(er) {
  var caught = false;

  // ignore errors on disposed domains.
  //
  // XXX This is a bit stupid.  We should probably get rid of
  // domain.dispose() altogether.  It's almost always a terrible
  // idea.  --isaacs
  if (this._disposed)
    return true;

  if (!util.isPrimitive(er)) {
    er.domain = this;
    er.domainThrown = true;
  }

  // The top-level domain-handler is handled separately.
  //
  // The reason is that if V8 was passed a command line option
  // asking it to abort on an uncaught exception (currently
  // "--abort-on-uncaught-exception"), we want an uncaught exception
  // in the top-level domain error handler to make the
  // process abort. Using try/catch here would always make V8 think
  // that these exceptions are caught, and thus would prevent it from
  // aborting in these cases.
  if (stack.length === 1) {
    // If there's no error handler, do not emit an 'error' event
    // as this would throw an error, make the process exit, and thus
    // prevent the process 'uncaughtException' event from being emitted
    // if a listener is set.
    if (EventEmitter.listenerCount(this, 'error') > 0) {
      try {
        // Set the _emittingTopLevelDomainError so that we know that, even
        // if technically the top-level domain is still active, it would
        // be ok to abort on an uncaught exception at this point
        process._emittingTopLevelDomainError = true;
        caught = this.emit('error', er);
      } finally {
        process._emittingTopLevelDomainError = false;
      }
    }
  } else {
    // wrap this in a try/catch so we don't get infinite throwing
    try {
      // One of three things will happen here.
      //
      // 1. There is a handler, caught = true
      // 2. There is no handler, caught = false
      // 3. It throws, caught = false
      //
      // If caught is false after this, then there's no need to exit()
      // the domain, because we're going to crash the process anyway.
      caught = this.emit('error', er);
    } catch (er2) {
      // The domain error handler threw!  oh no!
      // See if another domain can catch THIS error,
      // or else crash on the original one.
      // If the user already exited it, then don't double-exit.
      if (this === exports.active) {
        stack.pop();
      }
      if (stack.length) {
        exports.active = process.domain = stack[stack.length - 1];
        caught = process._fatalException(er2);
      } else {
        caught = false;
      }
    }
  }

  // Exit all domains on the stack.  Uncaught exceptions end the
  // current tick and no domains should be left on the stack
  // between ticks.
  stack.length = 0;
  exports.active = process.domain = null;

  return caught;
};
Example #11
0
TLSSocket.prototype._init = function(socket, wrap) {
  var self = this;
  var options = this._tlsOptions;
  var ssl = this._handle;

  // lib/net.js expect this value to be non-zero if write hasn't been flushed
  // immediately
  // TODO(indutny): rewise this solution, it might be 1 before handshake and
  // represent real writeQueueSize during regular writes.
  ssl.writeQueueSize = 1;

  this.server = options.server || null;

  // For clients, we will always have either a given ca list or be using
  // default one
  var requestCert = !!options.requestCert || !options.isServer,
      rejectUnauthorized = !!options.rejectUnauthorized;

  this._requestCert = requestCert;
  this._rejectUnauthorized = rejectUnauthorized;
  if (requestCert || rejectUnauthorized)
    ssl.setVerifyMode(requestCert, rejectUnauthorized);

  if (options.isServer) {
    ssl.onhandshakestart = onhandshakestart.bind(this);
    ssl.onhandshakedone = onhandshakedone.bind(this);
    ssl.onclienthello = onclienthello.bind(this);
    ssl.oncertcb = oncertcb.bind(this);
    ssl.onnewsession = onnewsession.bind(this);
    ssl.lastHandshakeTime = 0;
    ssl.handshakes = 0;

    if (this.server) {
      if (listenerCount(this.server, 'resumeSession') > 0 ||
          listenerCount(this.server, 'newSession') > 0) {
        ssl.enableSessionCallbacks();
      }
      if (listenerCount(this.server, 'OCSPRequest') > 0)
        ssl.enableCertCb();
    }
  } else {
    ssl.onhandshakestart = function() {};
    ssl.onhandshakedone = this._finishInit.bind(this);
    ssl.onocspresponse = onocspresponse.bind(this);

    if (options.session)
      ssl.setSession(options.session);
  }

  ssl.onerror = function(err) {
    if (self._writableState.errorEmitted)
      return;
    self._writableState.errorEmitted = true;

    // Destroy socket if error happened before handshake's finish
    if (!self._secureEstablished) {
      self._tlsError(err);
      self.destroy();
    } else if (options.isServer &&
               rejectUnauthorized &&
               /peer did not return a certificate/.test(err.message)) {
      // Ignore server's authorization errors
      self.destroy();
    } else {
      // Throw error
      self._tlsError(err);
    }
  };

  // If custom SNICallback was given, or if
  // there're SNI contexts to perform match against -
  // set `.onsniselect` callback.
  if (process.features.tls_sni &&
      options.isServer &&
      options.server &&
      (options.SNICallback !== SNICallback ||
       options.server._contexts.length)) {
    assert(typeof options.SNICallback === 'function');
    this._SNICallback = options.SNICallback;
    ssl.enableCertCb();
  }

  if (process.features.tls_npn && options.NPNProtocols)
    ssl.setNPNProtocols(options.NPNProtocols);

  if (options.handshakeTimeout > 0)
    this.setTimeout(options.handshakeTimeout, this._handleTimeout);

  // Socket already has some buffered data - emulate receiving it
  if (socket && socket._readableState && socket._readableState.length) {
    var buf;
    while ((buf = socket.read()) !== null)
      ssl.receive(buf);
  }

  if (socket instanceof net.Socket) {
    this._parent = socket;

    // To prevent assertion in afterConnect() and properly kick off readStart
    this._connecting = socket._connecting || !socket._handle;
    socket.once('connect', function() {
      self._connecting = false;
      self.emit('connect');
    });
  }

  // Assume `tls.connect()`
  if (wrap) {
    wrap.on('error', function(err) {
      self._tlsError(err);
    });
  } else {
    assert(!socket);
    this._connecting = true;
  }
};
Example #12
0
Domain.prototype._errorHandler = function(er) {
  var caught = false;

  if (!util.isPrimitive(er)) {
    Object.defineProperty(er, 'domain', {
      configurable: true,
      enumerable: false,
      value: this,
      writable: true
    });
    er.domainThrown = true;
  }

  // The top-level domain-handler is handled separately.
  //
  // The reason is that if V8 was passed a command line option
  // asking it to abort on an uncaught exception (currently
  // "--abort-on-uncaught-exception"), we want an uncaught exception
  // in the top-level domain error handler to make the
  // process abort. Using try/catch here would always make V8 think
  // that these exceptions are caught, and thus would prevent it from
  // aborting in these cases.
  if (stack.length === 1) {
    // If there's no error handler, do not emit an 'error' event
    // as this would throw an error, make the process exit, and thus
    // prevent the process 'uncaughtException' event from being emitted
    // if a listener is set.
    if (EventEmitter.listenerCount(this, 'error') > 0) {
      // Clear the uncaughtExceptionCaptureCallback so that we know that, even
      // if technically the top-level domain is still active, it would
      // be ok to abort on an uncaught exception at this point
      setUncaughtExceptionCaptureCallback(null);
      try {
        caught = this.emit('error', er);
      } finally {
        updateExceptionCapture();
      }
    }
  } else {
    // Wrap this in a try/catch so we don't get infinite throwing
    try {
      // One of three things will happen here.
      //
      // 1. There is a handler, caught = true
      // 2. There is no handler, caught = false
      // 3. It throws, caught = false
      //
      // If caught is false after this, then there's no need to exit()
      // the domain, because we're going to crash the process anyway.
      caught = this.emit('error', er);
    } catch (er2) {
      // The domain error handler threw!  oh no!
      // See if another domain can catch THIS error,
      // or else crash on the original one.
      // If the user already exited it, then don't double-exit.
      if (this === exports.active) {
        stack.pop();
      }
      updateExceptionCapture();
      if (stack.length) {
        exports.active = process.domain = stack[stack.length - 1];
        caught = process.domain._errorHandler(er2);
      } else {
        // Pass on to the next exception handler.
        throw er2;
      }
    }
  }

  // Exit all domains on the stack.  Uncaught exceptions end the
  // current tick and no domains should be left on the stack
  // between ticks.
  domainUncaughtExceptionClear();

  return caught;
};
Example #13
0
var func = function () {
  console.log('这个方法不会执行');
};

// 添加事件, 添加监听事件
server.on('request', func);
// 删除事件, 删除监听事件
server.removeListener('request', func);
// // 删除全部
// server.removeAllListeners('request');
//
// server.on('request', function (req, res) {
//     res.writeHead(200, {'Content-Type': 'text/plain'});
//     res.end('Hello, Event');
// });

// 设置最大值
// 默认最大值为10
server.setMaxListeners(20);

// 添加自定义事件
// customEvent 事件类型
server.on('customEvent', function () {
   console.log('此处为自定义事件');
});
// 执行自定义事件
server.emit('customEvent');


console.log(even.listenerCount(server, 'customEvent'));
Example #14
0
v8.on('newListener', function(name) {
  if (name === 'gc' && EventEmitter.listenerCount(this, name) === 0) {
    v8binding.startGarbageCollectionTracking(emitGC);
  }
});
Example #15
0
v8.on('removeListener', function(name) {
  if (name === 'gc' && EventEmitter.listenerCount(this, name) === 0) {
    v8binding.stopGarbageCollectionTracking();
  }
});
exports.ListenerCountByEvent = function (eventName){
    return events.listenerCount(eventEmitter, eventName);
}
Example #17
0
 _hasListeners(processedPath) {
   return this._events.listenerCount(processedPath) > 0;
 }
var EventEmmiter = require('events');
var e = new EventEmmiter();
function x1() {
    console.log(1);
}
//我们每一个函数都有最大监听数,默认10个
e.setMaxListeners(2);//warning 警告
e.once('休息1',x1);
//指定监听数量 x1的个数
console.log(e.listenerCount('休息1'));
//就近移除
// e.removeListener('休息',x1);
//清除所有的,此方法可以移除掉所有监听或者指定名字移除
// e.removeAllListeners('休息');
// e.emit('休息1');
console.log(e.listeners('休息1')); //获取当前函数池


Example #19
0
    console.log('이벤트 2');
});
myEvent.on('event2', () => {
    console.log('이벤트 2 추가');
});
myEvent.emit('event1');
myEvent.emit('event2');

myEvent.once('event3', () => {
    console.log('이벤트 3');
});
myEvent.emit('event3');
myEvent.emit('event3');

myEvent.on('event4', () => {
    console.log('이벤트 4');
});
myEvent.removeAllListeners('event4');
myEvent.emit('event4');

const listener = (msg) => {
    console.log(msg);
};
const event5Listener = listener.bind(undefined, '이벤트 5')
myEvent.on('event5', event5Listener);
myEvent.emit('event5');
myEvent.removeListener('event5', event5Listener);
myEvent.emit('event5');

console.log("myEvent.listenerCount('event2') ->", myEvent.listenerCount('event2'));
Example #20
0
/**
 * Created on 2016/7/7.
 */
var events = require('events');
var eventEmitter = new events.EventEmitter();

var listener1 = function () {
    console.log('listener1 call');
};
var listener2 = function () {
    console.log('listener2 call');
};

eventEmitter.addListener('connection', listener1);

eventEmitter.on('connection', listener2);

var count1 = events.listenerCount(eventEmitter, 'connection');
console.log('have ' + count1 + ' listeners');

eventEmitter.emit('connection');

eventEmitter.removeListener('connection', listener1);
console.log('remove listener:listener1');

var count2 = events.listenerCount(eventEmitter, 'connection');
console.log('have ' + count2 + ' listeners');

eventEmitter.emit('connection');

console.log('app end');