Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http: set socket timeout when socket connects #8895

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/_http_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: This is probably over-micro-optimizing, but using this instead of sock inside the callback would avoid allocating a closure every time here.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes sense. Used sock for readability but happy to fix it.

});
});

return this;
Expand Down
26 changes: 26 additions & 0 deletions test/parallel/test-http-client-timeout-on-connect.js
Original file line number Diff line number Diff line change
@@ -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();
}));
}));