【问题标题】:How to destroy a Node.js http.request connection nicely?如何很好地破坏 Node.js http.request 连接?
【发布时间】:2011-07-12 02:03:46
【问题描述】:

如果我在命令行中运行,程序会在client.destroy();之后停止

var client = http.get(options, 
        function(res) {
            console.log(res.statusCode);
            client.destroy();
          }
);

但是,当我将 client.destroy() 放在 res.on('end') 中时,情况并非如此:

var client = http.get(options, 
        function(res) {
            console.log(res.statusCode);
            res.on('end', function() {
                console.log("done");
                client.destroy();
            });
          }
);

它会抛出异常,因为 http.socket 为空。所以,我不能破坏它。

在这种情况下,程序执行将挂在那里并且不会结束。我能做些什么来阻止它? (除了 process.exit());

【问题讨论】:

    标签: http node.js request destroy


    【解决方案1】:

    如果是单个请求,您可以将 shouldKeepAlive 设置为 false

    var request = http.get(options, 
            function(res) {
                console.log(res.statusCode);
              }
    );
    request.shouldKeepAlive = false
    

    或发送Connection: close标头

    您无法访问套接字,因为它是 detached in the request 'end' event handler

    【讨论】:

    • 当我执行 'request.shouldKeepAlive" 时,它是否会影响套接字池中的任何内容?
    • 使用Connection header可能更好,这里分析-github.com/joyent/node/blob/master/lib/http.js#L442这会影响请求的shouldKeepAlive标志
    • 伙计们,停止在“master”中链接行号——没用——你不能在移动目标上链接行号。
    【解决方案2】:

    您的问题: http.get 或 http.request 创建的请求将默认关闭其套接字(连接)。您不必关闭它。

    您的代码示例: Nodejs 在你的 "res.on('end', yourCb)" 之前注册了 res.on('end', responseOnEnd)。 responseOnEnd 将关闭套接字。因为 responseOnEnd 在 yourCb 之前被调用,所以你不能在 res.on('end', yourCb) 中破坏套接字。

    【讨论】:

      【解决方案3】:

      致电res.req.destroy()

      见:https://nodejs.org/api/http.html#requestdestroyerror

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-24
        相关资源
        最近更新 更多