Nodejs原生的http.request 方法是不支持设置超时参数的,
而网络请求经常会遇到超时的情况,特别是对于外部网络,如果不处理超时,发起的请求将会一直卡主,消耗的系统资源也不能及时被释放。

定时器:通过定时器,当timeout事件触发的时候,主动调用req.abort() 终止请求,
然后返回超时异常。

  • 超时有请求超时(Request Timeout):HTTP客户端发起请求到接受到HTTP服务器端返回响应头的这段时间,
    如果超出设定时间,则表示请求超时。
  • 响应超时(Response Timeout):HTTP服务器端开始发送响应数据到HTTP客户端接收全部数据的这段时间,
    如果超出设定时间,则表示响应超时。
  1. var http = require(\'http\');
  2. var request_timer = null, req = null;
  3. // 请求5秒超时
  4. request_timer = setTimeout(function() {
  5. req.abort();
  6. console.log(\'Request Timeout.\');
  7. }, 5000);
  8. var options = {
  9. host: \'www.google.com\',
  10. port: 80,
  11. path: \'/\'
  12. };
  13. req = http.get(options, function(res) {
  14. clearTimeout(request_timer);
  15. // 等待响应60秒超时
  16. var response_timer = setTimeout(function() {
  17. res.destroy();
  18. console.log(\'Response Timeout.\');
  19. }, 60000);
  20. console.log("Got response: " + res.statusCode);
  21. var chunks = [], length = 0;
  22. res.on(\'data\', function(chunk) {
  23. length += chunk.length;
  24. chunks.push(chunk);
  25. });
  26. res.on(\'end\', function() {
  27. clearTimeout(response_timer);
  28. var data = new Buffer(length);
  29. // 延后copy
  30. for(var i=0, pos=0, size=chunks.length; i;>

^_^ 希望本文对你有用。

版权声明:本文为fengmk2原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/fengmk2/archive/2011/08/09/2132825.html