Skip to content

Commit d71ba32

Browse files
theanarkhtargos
authored andcommitted
http: fix http agent keep alive
PR-URL: #43380 Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Ricky Zhou <0x19951125@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
1 parent df50131 commit d71ba32

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

lib/_http_agent.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,11 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) {
342342
installListeners(this, s, options);
343343
cb(null, s);
344344
});
345-
345+
// When keepAlive is true, pass the related options to createConnection
346+
if (this.keepAlive) {
347+
options.keepAlive = this.keepAlive;
348+
options.keepAliveInitialDelay = this.keepAliveMsecs;
349+
}
346350
const newSocket = this.createConnection(options, oncreate);
347351
if (newSocket)
348352
oncreate(null, newSocket);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('assert');
5+
const http = require('http');
6+
const { Agent } = require('_http_agent');
7+
8+
const agent = new Agent({
9+
keepAlive: true,
10+
keepAliveMsecs: 1000,
11+
});
12+
13+
const server = http.createServer(common.mustCall((req, res) => {
14+
res.end('ok');
15+
}));
16+
17+
server.listen(0, common.mustCall(() => {
18+
const createConnection = agent.createConnection;
19+
agent.createConnection = (options, ...args) => {
20+
assert.strictEqual(options.keepAlive, true);
21+
assert.strictEqual(options.keepAliveInitialDelay, agent.keepAliveMsecs);
22+
return createConnection.call(agent, options, ...args);
23+
};
24+
http.get({
25+
host: 'localhost',
26+
port: server.address().port,
27+
agent: agent,
28+
path: '/'
29+
}, common.mustCall((res) => {
30+
// for emit end event
31+
res.on('data', () => {});
32+
res.on('end', () => {
33+
server.close();
34+
});
35+
}));
36+
}));

0 commit comments

Comments
 (0)