Permalink
Browse files

add a generic emitter to Socket that emits for ALL sockets

  • Loading branch information...
1 parent 91e87d6 commit fa4c874f3f47bc3330ab7a6c5995b4a13cbae009 @thejh committed Dec 3, 2011
Showing with 26 additions and 6 deletions.
  1. +26 −6 lib/net.js
View
@@ -115,6 +115,11 @@ function Socket(options) {
stream.Stream.call(this);
+ if (Socket.genericEmitter != null) {
+ this.on('connect', Socket.genericEmitter.emit.bind(Socket.genericEmitter, this, 'connect'));
+ this.on('close', Socket.genericEmitter.emit.bind(Socket.genericEmitter, this, 'close'));
+ }
+
if (typeof options == 'number') {
// Legacy interface.
// Must support legacy interface. NPM depends on it.
@@ -143,6 +148,14 @@ exports.Socket = Socket;
exports.Stream = Socket; // Legacy naming.
+Socket.addGenericListener = function(event, listener) {
+ if (Socket.genericEmitter == null) {
+ Socket.genericEmitter = new events.EventEmitter;
+ }
+ Socket.genericEmitter.on(event, listener);
+};
+
+
Socket.prototype.listen = function() {
var self = this;
self.on('connection', arguments[0]);
@@ -333,16 +346,19 @@ function onread(buffer, offset, length) {
if (buffer) {
// Emit 'data' event.
+ var data = buffer.slice(offset, end);
+
+ if (Socket.genericEmitter != null) {
+ Socket.genericEmitter.emit(self, 'data', data);
+ }
+
if (self._decoder) {
// Emit a string.
- var string = self._decoder.write(buffer.slice(offset, end));
+ var string = self._decoder.write(data);
if (string.length) self.emit('data', string);
} else {
- // Emit a slice. Attempt to avoid slicing the buffer if no one is
- // listening for 'data'.
- if (self._events && self._events['data']) {
- self.emit('data', buffer.slice(offset, end));
- }
+ // Emit a slice.
+ self.emit('data', data);
}
self.bytesRead += length;
@@ -445,6 +461,10 @@ Socket.prototype.write = function(data, arg1, arg2) {
Socket.prototype._write = function(data, encoding, cb) {
timers.active(this);
+ if (Socket.genericEmitter != null) {
+ Socket.genericEmitter.emit('write', this, data);
+ }
+
// `encoding` is unused right now, `data` is always a buffer.
var writeReq = this._handle.write(data);

0 comments on commit fa4c874

Please sign in to comment.