From 10be20a0e88f2b8aa354884a418b92c331fe078d Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Sun, 2 Oct 2016 12:10:33 +0200 Subject: [PATCH] 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: https://github.com/nodejs/node/pull/8895 Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater Reviewed-By: Matteo Collina Reviewed-By: Joyee Cheung --- lib/_http_client.js | 4 ++- .../test-http-client-timeout-on-connect.js | 26 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-http-client-timeout-on-connect.js diff --git a/lib/_http_client.js b/lib/_http_client.js index e972a3d5b9e9fd..a0e4fb2507c265 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -739,7 +739,9 @@ ClientRequest.prototype.setTimeout = function setTimeout(msecs, callback) { } this.once('socket', function(sock) { - sock.setTimeout(msecs, emitTimeout); + sock.once('connect', function() { + sock.setTimeout(msecs, emitTimeout); + }); }); return this; diff --git a/test/parallel/test-http-client-timeout-on-connect.js b/test/parallel/test-http-client-timeout-on-connect.js new file mode 100644 index 00000000000000..af3b3ef53debc2 --- /dev/null +++ b/test/parallel/test-http-client-timeout-on-connect.js @@ -0,0 +1,26 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); + +const server = http.createServer((req, res) => { + // This space is intentionally left blank. +}); + +server.listen(0, common.localhostIPv4, common.mustCall(() => { + const port = server.address().port; + const req = http.get(`http://${common.localhostIPv4}:${port}`); + + req.setTimeout(1); + req.on('socket', common.mustCall((socket) => { + assert.strictEqual(socket._idleTimeout, undefined); + socket.on('connect', common.mustCall(() => { + assert.strictEqual(socket._idleTimeout, 1); + })); + })); + req.on('timeout', common.mustCall(() => req.abort())); + req.on('error', common.mustCall((err) => { + assert.strictEqual('socket hang up', err.message); + server.close(); + })); +}));