在nodejs中进行http请求,设置超时,如果是req.abort() 那么http 请求还会是继续的,但是re.destory()就会彻底中止,他们详细区别是什么?
还有个超时问题,分为请求超时和响应超时,以前没这个概念,最近才认识到这个细节,我想问问这两个分别意味着什么?测试一个资源快慢,应该以哪个为标准?
var http = require('http');
var request_timer = null, req = null;
request_timer = setTimeout(function() {
req.destroy();
console.log('Request Timeout.');
console.log('1');
}, 1000);
// 请求5秒超时
var options = {
host: 'www.baidu.com',
port: 80,
path: '/'
}
req = http.get(options, function(e) {
clearTimeout(request_timer);
}).on('error', function(err) {
if(request_timer) {
clearTimeout(request_timer);
console.log('2');
}
console.log('3');
});
假设 timeout设置为 1ms(测试强制超时),req.destroy()
的话 超时输出到3
,直接退出,但是如果是req.abort()
的话,等到输出3
会过一会才会退出,按照nightire
的说法,可能是请求已经发出,等待响应,所以req.abort()是没有影响的。
PHP中文网2017-04-17 11:10:57
Thanks for the invitation, I’m on my way home, so I’ll keep the story short:
request.abort()
will abort an already issued request, but I don’t understand what you mean by saying that the request will continue. Are you saying that executing it has no effect?
re.destroy()
? I only know socket.destroy()
, I don’t know what you are referring to? socket.destroy()
Will block all I/O activities on the current socket, not just HTTP requests. This is usually used to respond to errors, not to cancel the request. But I don't know what the re
in your question refers to, the response
object? It seems there is no destroy
method.
The request goes out and the response comes back. These two timeouts must occur at different stages. You ask what it means... I think it's already obvious. If one goes out and the other comes back, what else can it mean?
As for testing the speed of a resource, it should be evaluated based on the consumption of requests and responses. If your request for the resource does not get a response for a long time, you will feel slow; if your request gets a response quickly, but the transmission speed is crashing, you will still feel slow. vice versa.
迷茫2017-04-17 11:10:57
re.destroy()
This is a method inherited from socket. After calling it, socket.destroy() is actually called.
The abort() method will also call the socket’s destruction
///This is the official source code of node http.js package
ClientRequest.prototype.abort = function() {
// If we're aborting, we don't care about any more response data.
if (this.res)
this.res._dump();
else
this.once('response', function(res) {
res._dump();
});
if (this.socket) {
// in-progress
this.socket.destroy();////Pay attention here
} else {
// haven't been assigned a socket yet.
// this could be more efficient, it could
// remove itself from the pending requests
this._deferToConnect('destroy', []);
}
};
//You can see the relationship about() will be cleaner