From 2f93eb6102fc7f226e2bca641d6e1bcee14037e4 Mon Sep 17 00:00:00 2001 From: isaacs Date: Wed, 2 May 2012 12:13:54 -0700 Subject: [PATCH] http client: Destroy on timeout --- lib/http.js | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/lib/http.js b/lib/http.js index 05de4c084cd..8d2a7e7b409 100644 --- a/lib/http.js +++ b/lib/http.js @@ -1443,6 +1443,7 @@ ClientRequest.prototype.onSocket = function(socket) { }); }; + ClientRequest.prototype._deferToConnect = function(method, arguments_, cb) { // This function is for calls that need to happen once the socket is // connected and writable. It's an important promisy thing for all the socket @@ -1471,9 +1472,33 @@ ClientRequest.prototype._deferToConnect = function(method, arguments_, cb) { onSocket(); } }; -ClientRequest.prototype.setTimeout = function() { - this._deferToConnect('setTimeout', arguments); + +ClientRequest.prototype.setTimeout = function(msecs, callback) { + if (callback) this.once('timeout', callback); + + var self = this; + function emitTimeout() { + self.emit('timeout'); + self.destroy(new Error('timeout')); + } + + if (this.socket && this.socket.writable) { + this.socket.setTimeout(msecs, emitTimeout); + return; + } + + if (this.socket) { + this.socket.on('connect', function() { + this.setTimeout(msecs, emitTimeout); + }); + return; + } + + this.on('socket', function(sock) { + this.setTimeout(msecs, emitTimeout); + }); }; + ClientRequest.prototype.setNoDelay = function() { this._deferToConnect('setNoDelay', arguments); }; @@ -1566,7 +1591,7 @@ function connectionListener(socket) { httpSocketSetup(socket); socket.setTimeout(2 * 60 * 1000); // 2 minute timeout - socket.addListener('timeout', function() { + socket.once('timeout', function() { socket.destroy(); });