diff --git a/lib/net.js b/lib/net.js index a6c95c6857b9b2..5bf2f292fb76eb 100644 --- a/lib/net.js +++ b/lib/net.js @@ -1038,6 +1038,7 @@ function Server(options, connectionListener) { this._handle = null; this._usingSlaves = false; this._slaves = []; + this._unref = false; this.allowHalfOpen = options.allowHalfOpen || false; this.pauseOnConnect = !!options.pauseOnConnect; @@ -1171,6 +1172,10 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { // generate connection key, this should be unique to the connection this._connectionKey = addressType + ':' + address + ':' + port; + // unref the handle if the server was unref'ed prior to listening + if (this._unref) + this.unref(); + process.nextTick(function() { // ensure handle hasn't closed if (self._handle) @@ -1440,11 +1445,15 @@ Server.prototype._setupSlave = function(socketList) { }; Server.prototype.ref = function() { + this._unref = false; + if (this._handle) this._handle.ref(); }; Server.prototype.unref = function() { + this._unref = true; + if (this._handle) this._handle.unref(); }; diff --git a/test/parallel/test-net-server-unref-persistent.js b/test/parallel/test-net-server-unref-persistent.js new file mode 100644 index 00000000000000..3a5092b92e0b8f --- /dev/null +++ b/test/parallel/test-net-server-unref-persistent.js @@ -0,0 +1,20 @@ +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var closed = false; +var server = net.createServer(); + +// unref before listening +server.unref(); +server.listen(); + +// If the timeout fires, that means the server held the event loop open +// and the unref() was not persistent. Close the server and fail the test. +setTimeout(function() { + closed = true; + server.close(); +}, 1000).unref(); + +process.on('exit', function() { + assert.strictEqual(closed, false, 'server should not hold loop open'); +});