From 95d6aad8729a4ab4279e11c9e92d4efeace91d03 Mon Sep 17 00:00:00 2001 From: theanarkh <2923878201@qq.com> Date: Sat, 11 Jun 2022 19:16:19 +0800 Subject: [PATCH] http: fix http agent keep alive --- lib/_http_agent.js | 6 +++++- test/parallel/test-http-agent-keepalive.js | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 6784e8848599863..791a43c8d5d029b 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -342,7 +342,11 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) { installListeners(this, s, options); cb(null, s); }); - + // When keepAlive is true, pass the related options to createConnection + if (this.keepAlive) { + options.keepAlive = this.keepAlive; + options.keepAliveInitialDelay = this.keepAliveMsecs; + } const newSocket = this.createConnection(options, oncreate); if (newSocket) oncreate(null, newSocket); diff --git a/test/parallel/test-http-agent-keepalive.js b/test/parallel/test-http-agent-keepalive.js index f7424634df1bd52..d3cbf6c9d216f3a 100644 --- a/test/parallel/test-http-agent-keepalive.js +++ b/test/parallel/test-http-agent-keepalive.js @@ -81,6 +81,17 @@ function second() { })); } +function checkSocketKeepAlive(socket) { + const symbols = Object.getOwnPropertySymbols(socket); + for (let i = 0; i < symbols.length; i++) { + const symbol = symbols[i]; + if (symbol.toString() === 'Symbol(kSetKeepAliveInitialDelay)') { + assert.strictEqual(socket[symbol], agent.keepAliveMsecs / 1000); + return; + } + } +} + function remoteClose() { // Mock remote server close the socket const req = get('/remote_close', common.mustCall((res) => { @@ -94,6 +105,7 @@ function remoteClose() { assert.strictEqual(agent.sockets[name], undefined); assert.strictEqual(agent.freeSockets[name].length, 1); assert.strictEqual(agent.totalSocketCount, 1); + checkSocketKeepAlive(agent.freeSockets[name][0]); // Waiting remote server close the socket setTimeout(common.mustCall(() => { assert.strictEqual(agent.sockets[name], undefined);