Skip to content

Commit ffed6ef

Browse files
committed
Merge pull request #605 from sebpiq/master
Clean event handlers on WebSocketServer's internal http server when closing
2 parents 0d1fb9c + 44d9e1c commit ffed6ef

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

lib/WebSocketServer.js

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,15 @@ function WebSocketServer(options, callback) {
7373
this._server._webSocketPaths[options.value.path] = 1;
7474
}
7575
}
76-
if (this._server) this._server.once('listening', function() { self.emit('listening'); });
76+
if (this._server) {
77+
this._onceServerListening = function() { self.emit('listening'); };
78+
this._server.once('listening', this._onceServerListening);
79+
}
7780

7881
if (typeof this._server != 'undefined') {
79-
this._server.on('error', function(error) {
80-
self.emit('error', error)
81-
});
82-
this._server.on('upgrade', function(req, socket, upgradeHead) {
82+
this._onServerError = function(error) { self.emit('error', error) };
83+
this._server.on('error', this._onServerError);
84+
this._onServerUpgrade = function(req, socket, upgradeHead) {
8385
//copy upgradeHead to avoid retention of large slab buffers used in node core
8486
var head = new Buffer(upgradeHead.length);
8587
upgradeHead.copy(head);
@@ -88,7 +90,8 @@ function WebSocketServer(options, callback) {
8890
self.emit('connection'+req.url, client);
8991
self.emit('connection', client);
9092
});
91-
});
93+
};
94+
this._server.on('upgrade', this._onServerUpgrade);
9295
}
9396

9497
this.options = options.value;
@@ -135,6 +138,11 @@ WebSocketServer.prototype.close = function(callback) {
135138
}
136139
}
137140
finally {
141+
if (this._server) {
142+
this._server.removeListener('listening', this._onceServerListening);
143+
this._server.removeListener('error', this._onServerError);
144+
this._server.removeListener('upgrade', this._onServerUpgrade);
145+
}
138146
delete this._server;
139147
}
140148
if(callback)

test/WebSocketServer.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,18 @@ describe('WebSocketServer', function() {
247247
});
248248
});
249249

250+
it('cleans event handlers on precreated server', function(done) {
251+
var srv = http.createServer();
252+
srv.listen(++port, function() {
253+
var wss = new WebSocketServer({server: srv});
254+
wss.close();
255+
srv.emit('upgrade');
256+
srv.on('error', function() {});
257+
srv.emit('error');
258+
done()
259+
});
260+
});
261+
250262
it('cleans up websocket data on a precreated server', function(done) {
251263
var srv = http.createServer();
252264
srv.listen(++port, function () {

0 commit comments

Comments
 (0)