@@ -26,6 +26,7 @@ function Socket (id, server, transport, req) {
26
26
this . writeBuffer = [ ] ;
27
27
this . packetsFn = [ ] ;
28
28
this . sentCallbackFn = [ ] ;
29
+ this . cleanupFn = [ ] ;
29
30
this . request = req ;
30
31
31
32
// Cache IP since it might not be in the req later
@@ -140,13 +141,25 @@ Socket.prototype.setPingTimeout = function () {
140
141
*/
141
142
142
143
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
+
143
149
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 ) ;
148
154
//this function will manage packet events (also message callbacks)
149
155
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
+ } ) ;
150
163
} ;
151
164
152
165
/**
@@ -251,6 +264,9 @@ Socket.prototype.maybeUpgrade = function (transport) {
251
264
*/
252
265
253
266
Socket . prototype . clearTransport = function ( ) {
267
+ var cleanup ;
268
+ while ( cleanup = this . cleanupFn . shift ( ) ) cleanup ( ) ;
269
+
254
270
// silence further transport errors and prevent uncaught exceptions
255
271
this . transport . on ( 'error' , function ( ) {
256
272
debug ( 'error triggered by discarded transport' ) ;
@@ -296,8 +312,14 @@ Socket.prototype.onClose = function (reason, description) {
296
312
297
313
Socket . prototype . setupSendCallback = function ( ) {
298
314
var self = this ;
315
+ this . transport . on ( 'drain' , onDrain ) ;
316
+
317
+ this . cleanupFn . push ( function ( ) {
318
+ self . transport . removeListener ( 'drain' , onDrain ) ;
319
+ } ) ;
320
+
299
321
//the message was sent successfully, execute the callback
300
- this . transport . on ( 'drain' , function ( ) {
322
+ function onDrain ( ) {
301
323
if ( self . sentCallbackFn . length > 0 ) {
302
324
var seqFn = self . sentCallbackFn . splice ( 0 , 1 ) [ 0 ] ;
303
325
if ( 'function' == typeof seqFn ) {
@@ -312,7 +334,7 @@ Socket.prototype.setupSendCallback = function () {
312
334
}
313
335
}
314
336
}
315
- } ) ;
337
+ }
316
338
} ;
317
339
318
340
/**
0 commit comments