Skip to content

Commit 4cb17cb

Browse files
committed
net: fix net.connect() resource leak
The 'connect' event listener was attached with .on(), which blocked it from getting garbage collected. Use .once() instead. Fixes #4308.
1 parent fb5c7f0 commit 4cb17cb

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

lib/net.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -665,7 +665,7 @@ Socket.prototype.connect = function(options, cb) {
665665
}
666666

667667
if (typeof cb === 'function') {
668-
self.on('connect', cb);
668+
self.once('connect', cb);
669669
}
670670

671671
timers.active(this);
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Copyright Joyent, Inc. and other Node contributors.
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a
4+
// copy of this software and associated documentation files (the
5+
// "Software"), to deal in the Software without restriction, including
6+
// without limitation the rights to use, copy, modify, merge, publish,
7+
// distribute, sublicense, and/or sell copies of the Software, and to permit
8+
// persons to whom the Software is furnished to do so, subject to the
9+
// following conditions:
10+
//
11+
// The above copyright notice and this permission notice shall be included
12+
// in all copies or substantial portions of the Software.
13+
//
14+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15+
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16+
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17+
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18+
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19+
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20+
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21+
22+
// Flags: --expose-gc
23+
24+
var common = require('../common');
25+
var assert = require('assert');
26+
var net = require('net');
27+
28+
assert(typeof gc === 'function', 'Run this test with --expose-gc');
29+
net.createServer(function() {}).listen(common.PORT);
30+
31+
(function() {
32+
// 2**26 == 64M entries
33+
for (var i = 0, junk = [123.456]; i < 26; ++i) junk = junk.concat(junk);
34+
35+
net.createConnection(common.PORT, '127.0.0.1', function() {
36+
assert(junk.length != 0); // keep reference alive
37+
setTimeout(done, 10);
38+
gc();
39+
});
40+
})();
41+
42+
function done() {
43+
var before = process.memoryUsage().rss;
44+
gc();
45+
var after = process.memoryUsage().rss;
46+
var reclaimed = (before - after) / 1024;
47+
console.log('%d kB reclaimed', reclaimed);
48+
assert(reclaimed > 256 * 1024); // it's more like 512M on x64
49+
process.exit();
50+
}

0 commit comments

Comments
 (0)