http client: Destroy on timeout

This commit is contained in:
isaacs 2012-05-02 12:13:54 -07:00
parent 0a414f4caa
commit 2f93eb6102

View File

@ -1443,6 +1443,7 @@ ClientRequest.prototype.onSocket = function(socket) {
}); });
}; };
ClientRequest.prototype._deferToConnect = function(method, arguments_, cb) { ClientRequest.prototype._deferToConnect = function(method, arguments_, cb) {
// This function is for calls that need to happen once the socket is // 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 // 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(); 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() { ClientRequest.prototype.setNoDelay = function() {
this._deferToConnect('setNoDelay', arguments); this._deferToConnect('setNoDelay', arguments);
}; };
@ -1566,7 +1591,7 @@ function connectionListener(socket) {
httpSocketSetup(socket); httpSocketSetup(socket);
socket.setTimeout(2 * 60 * 1000); // 2 minute timeout socket.setTimeout(2 * 60 * 1000); // 2 minute timeout
socket.addListener('timeout', function() { socket.once('timeout', function() {
socket.destroy(); socket.destroy();
}); });