Skip to content

Commit 10be20a

Browse files
lpincaBridgeAR
authored andcommitted
http: set socket timeout when socket connects
`request.setTimeout()` calls `socket.setTimeout()` as soon as a socket is assigned to the request. This makes the `timeout` event to be emitted on the request even if the underlying socket never connects. This commit makes `socket.setTimeout()` to be called only when the underlying socket is connected. PR-URL: #8895 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Joyee Cheung <[email protected]>
1 parent c5eb5bf commit 10be20a

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

lib/_http_client.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -739,7 +739,9 @@ ClientRequest.prototype.setTimeout = function setTimeout(msecs, callback) {
739739
}
740740

741741
this.once('socket', function(sock) {
742-
sock.setTimeout(msecs, emitTimeout);
742+
sock.once('connect', function() {
743+
sock.setTimeout(msecs, emitTimeout);
744+
});
743745
});
744746

745747
return this;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const http = require('http');
5+
6+
const server = http.createServer((req, res) => {
7+
// This space is intentionally left blank.
8+
});
9+
10+
server.listen(0, common.localhostIPv4, common.mustCall(() => {
11+
const port = server.address().port;
12+
const req = http.get(`http://${common.localhostIPv4}:${port}`);
13+
14+
req.setTimeout(1);
15+
req.on('socket', common.mustCall((socket) => {
16+
assert.strictEqual(socket._idleTimeout, undefined);
17+
socket.on('connect', common.mustCall(() => {
18+
assert.strictEqual(socket._idleTimeout, 1);
19+
}));
20+
}));
21+
req.on('timeout', common.mustCall(() => req.abort()));
22+
req.on('error', common.mustCall((err) => {
23+
assert.strictEqual('socket hang up', err.message);
24+
server.close();
25+
}));
26+
}));

0 commit comments

Comments
 (0)