From c27278832dcdfa0e2b3a68be44000bfe22c3d177 Mon Sep 17 00:00:00 2001 From: Tareq Sharafy Date: Mon, 2 Jul 2018 17:33:10 +0300 Subject: [PATCH] close free sockets --- index.js | 10 ++++++++++ test/test.js | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/index.js b/index.js index 1c50116..0ee6b29 100644 --- a/index.js +++ b/index.js @@ -94,6 +94,7 @@ Agent.prototype.addRequest = function addRequest(req, _opts) { let timeout; let timedOut = false; const timeoutMs = this.timeout; + const freeSocket = this.freeSocket; function onerror(err) { if (req._hadError) return; @@ -133,6 +134,10 @@ Agent.prototype.addRequest = function addRequest(req, _opts) { // responsibility for this `req` to the Agent from here on socket.addRequest(req, opts); } else if (socket) { + function onfree() { + freeSocket(socket, opts); + } + socket.on('free', onfree); req.onSocket(socket); } else { const err = new Error( @@ -158,3 +163,8 @@ Agent.prototype.addRequest = function addRequest(req, _opts) { Promise.reject(err).catch(callbackError); } }; + +Agent.prototype.freeSocket = function freeSocket(socket, opts) { + // TODO reuse sockets + socket.destroy(); +}; diff --git a/test/test.js b/test/test.js index da2e919..6a8ca68 100644 --- a/test/test.js +++ b/test/test.js @@ -398,6 +398,30 @@ describe('"http" module', function() { }); }); + it('should free sockets after use', function(done) { + var agent = new Agent(function(req, opts, fn) { + var socket = net.connect(opts); + fn(null, socket); + }); + + // add HTTP server "request" listener + var gotReq = false; + server.once('request', function(req, res) { + gotReq = true; + res.end(); + }); + + var info = url.parse('http://127.0.0.1:' + port + '/foo'); + info.agent = agent; + http.get(info, function(res) { + res.socket.emit('free'); + assert.equal(true, res.socket.destroyed); + assert(gotReq); + done(); + }); + }); + + describe('PassthroughAgent', function() { it('should pass through to `http.globalAgent`', function(done) { // add HTTP server "request" listener