Skip to content

Commit d8eb974

Browse files
cjihrigbrendanashworth
authored andcommitted
net: make Server.prototype.unref() persistent
Currently, the unref() method does not remember any state if called before the server's handle has been created. This commit adds state to track calls to ref() and unref(). PR-URL: #897 Reviewed-By: Evan Lucas <[email protected]> Reviewed-By: Brendan Ashworth <[email protected]>
1 parent 26ebe98 commit d8eb974

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

lib/net.js

+9
Original file line numberDiff line numberDiff line change
@@ -1038,6 +1038,7 @@ function Server(options, connectionListener) {
10381038
this._handle = null;
10391039
this._usingSlaves = false;
10401040
this._slaves = [];
1041+
this._unref = false;
10411042

10421043
this.allowHalfOpen = options.allowHalfOpen || false;
10431044
this.pauseOnConnect = !!options.pauseOnConnect;
@@ -1171,6 +1172,10 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
11711172
// generate connection key, this should be unique to the connection
11721173
this._connectionKey = addressType + ':' + address + ':' + port;
11731174

1175+
// unref the handle if the server was unref'ed prior to listening
1176+
if (this._unref)
1177+
this.unref();
1178+
11741179
process.nextTick(function() {
11751180
// ensure handle hasn't closed
11761181
if (self._handle)
@@ -1440,11 +1445,15 @@ Server.prototype._setupSlave = function(socketList) {
14401445
};
14411446

14421447
Server.prototype.ref = function() {
1448+
this._unref = false;
1449+
14431450
if (this._handle)
14441451
this._handle.ref();
14451452
};
14461453

14471454
Server.prototype.unref = function() {
1455+
this._unref = true;
1456+
14481457
if (this._handle)
14491458
this._handle.unref();
14501459
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
var common = require('../common');
2+
var assert = require('assert');
3+
var net = require('net');
4+
var closed = false;
5+
var server = net.createServer();
6+
7+
// unref before listening
8+
server.unref();
9+
server.listen();
10+
11+
// If the timeout fires, that means the server held the event loop open
12+
// and the unref() was not persistent. Close the server and fail the test.
13+
setTimeout(function() {
14+
closed = true;
15+
server.close();
16+
}, 1000).unref();
17+
18+
process.on('exit', function() {
19+
assert.strictEqual(closed, false, 'server should not hold loop open');
20+
});

0 commit comments

Comments
 (0)