【问题标题】:How to set Timeout for http.createClient in Node.js?如何在 Node.js 中为 http.createClient 设置超时?
【发布时间】:2011-09-02 00:32:12
【问题描述】:

有一个帖子:How do I set a timeout for client http connections in node.js

但没有一个答案会奏效。

所以,我有这样的代码:

    var remote_client = http.createClient(myPost, myHost);
    var path = '/getData?';
    var param = {       };

    var request = remote_client.request("POST", path,);

    // error case
    remote_client.addListener('error', function(connectionException){
        console.log("Nucleus Error: " + connectionException);
        next(connectionException);
    });

    request.addListener('response', function (response) {
        response.setEncoding('utf-8'); 
        var body = '';

        response.addListener('data', function (chunk) {

        // get the result!              
        });
    });

    request.end();

最大的问题是我连接的 url 可能会超时。因此,我想设置一个超时时间,比如 15 秒。如果是这样,触发一个监听器。

但是,我在 http.createClient 的文档中没有看到任何超时功能。请指教。谢谢。 :)

【问题讨论】:

标签: node.js timeout


【解决方案1】:
var foo = setTimeout(function() {
    request.emit("timeout-foo");
}, 15000);

// listen to timeout
request.on("timeout-foo", function() { });

request.addListener('response', function (response) {
    // bla
    // clear counter
    clearTimeout(foo);
});

只需自己运行计数器。

【讨论】:

  • github.com/mikeal/request/issues/25 - 这个库是建立在 http/client 之上的,所以听起来它在节点核心 http 客户端中并不是一个真正的特性——同意 Raynos
  • 谢谢。我也有一个问题。对于代码,它设置了请求的超时时间。我需要为响应设置另一个超时处理程序吗?例如 response.addListener('data', ... );并添加一个这样的: response.on('data-timeout', ...);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 2014-06-13
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
相关资源
最近更新 更多