Skip to content

Commit 02f9ed8

Browse files
committed
remove listeners upon clearTransport
1 parent d74b3c7 commit 02f9ed8

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

lib/socket.js

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ function Socket (id, server, transport, req) {
2626
this.writeBuffer = [];
2727
this.packetsFn = [];
2828
this.sentCallbackFn = [];
29+
this.cleanupFn = [];
2930
this.request = req;
3031

3132
// Cache IP since it might not be in the req later
@@ -140,13 +141,25 @@ Socket.prototype.setPingTimeout = function () {
140141
*/
141142

142143
Socket.prototype.setTransport = function (transport) {
144+
var onError = this.onError.bind(this);
145+
var onPacket = this.onPacket.bind(this);
146+
var flush = this.flush.bind(this);
147+
var onClose = this.onClose.bind(this, 'transport close');
148+
143149
this.transport = transport;
144-
this.transport.once('error', this.onError.bind(this));
145-
this.transport.on('packet', this.onPacket.bind(this));
146-
this.transport.on('drain', this.flush.bind(this));
147-
this.transport.once('close', this.onClose.bind(this, 'transport close'));
150+
this.transport.once('error', onError);
151+
this.transport.on('packet', onPacket);
152+
this.transport.on('drain', flush);
153+
this.transport.once('close', onClose);
148154
//this function will manage packet events (also message callbacks)
149155
this.setupSendCallback();
156+
157+
this.cleanupFn.push(function() {
158+
transport.removeListener('error', onError);
159+
transport.removeListener('packet', onPacket);
160+
transport.removeListener('drain', flush);
161+
transport.removeListener('close', onClose);
162+
});
150163
};
151164

152165
/**
@@ -251,6 +264,9 @@ Socket.prototype.maybeUpgrade = function (transport) {
251264
*/
252265

253266
Socket.prototype.clearTransport = function () {
267+
var cleanup;
268+
while (cleanup = this.cleanupFn.shift()) cleanup();
269+
254270
// silence further transport errors and prevent uncaught exceptions
255271
this.transport.on('error', function(){
256272
debug('error triggered by discarded transport');
@@ -296,8 +312,14 @@ Socket.prototype.onClose = function (reason, description) {
296312

297313
Socket.prototype.setupSendCallback = function () {
298314
var self = this;
315+
this.transport.on('drain', onDrain);
316+
317+
this.cleanupFn.push(function() {
318+
self.transport.removeListener('drain', onDrain);
319+
});
320+
299321
//the message was sent successfully, execute the callback
300-
this.transport.on('drain', function() {
322+
function onDrain() {
301323
if (self.sentCallbackFn.length > 0) {
302324
var seqFn = self.sentCallbackFn.splice(0,1)[0];
303325
if ('function' == typeof seqFn) {
@@ -312,7 +334,7 @@ Socket.prototype.setupSendCallback = function () {
312334
}
313335
}
314336
}
315-
});
337+
}
316338
};
317339

318340
/**

0 commit comments

Comments
 (0)