如何很好地销毁 Node.js http.request 连接?
如果我在命令行中运行它,程序将在 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 为 null。所以,我无法摧毁它。
在这种情况下,程序执行将挂在那里并且不会结束。我能做什么来阻止它? (process.exit() 除外);
If I run it in the command line, the program will stop after client.destroy();
var client = http.get(options,
function(res) {
console.log(res.statusCode);
client.destroy();
}
);
However, it is not the case when I put the client.destroy() inside the res.on('end'):
var client = http.get(options,
function(res) {
console.log(res.statusCode);
res.on('end', function() {
console.log("done");
client.destroy();
});
}
);
It will throw exception because the http.socket is null. so, I can't destroy it.
IN this case, the program execution will hang there and will not end. What can I do to stop it? (other than process.exit());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果是单个请求,您可以将 shouldKeepAlive 设置为 false
或发送
Connection: close
标头您无法访问套接字,因为它是 分离 在 请求“结束”事件处理程序
if it's single request you can just set shouldKeepAlive to false
or send
Connection: close
headerYou can't access socket because it is detached in the request 'end' event handler
调用res.req.destroy()。
请参阅:https://nodejs.org/api/http.html#requestdestroyerror
Call
res.req.destroy()
.See: https://nodejs.org/api/http.html#requestdestroyerror
针对您的问题:
由 http.get 或 http.request 创建的请求将默认关闭其套接字(连接)。你不必关闭它。
您的代码示例:
Nodejs 已在“res.on('end', yourCb)”之前注册了 res.on('end', responseOnEnd)。
responseOnEnd 将关闭套接字。因为responseOnEnd是在yourCb之前调用的,所以你不能在res.on('end', yourCb)中销毁套接字。
To your question:
request created by http.get or http.request will close its socket(connection) by default. You don't have to close it.
To your code example:
Nodejs has registered res.on('end', responseOnEnd) before your "res.on('end', yourCb)".
responseOnEnd will close the socket. Because responseOnEnd is called before yourCb,so you can't destory the socket in res.on('end', yourCb) .