即使客户端断开连接,Node.js服务器也会保留流数据 [英] Node.js server keeps streaming data even after client disconnected
问题描述
我有一个小型Node.js + express服务器,它有一个虚拟下载方法:
I have a small Node.js + express server which has a dummy download method:
app.get("/download",function(req,res) {
res.set('Content-Type', 'application/octet-stream');
res.set('Content-Length', 1000000000011);
res.set('Connection', 'keep-alive');
res.set('Content-Disposition', 'attachment; filename="file.zip"');
var interval = setInterval(function(){
res.write(00000000);
var dateStr = new Date().toISOString();
console.log(dateStr + " writing bits...");
},500);
});
问题是我关闭浏览器后仍然看到节点服务器正在传输数据。
如何检测客户端何时断开连接并停止流式传输?
The problem is that after I close the browser I still see that the node server is transferring data. How can I detect when the client is disconnected and stop the streaming?
我尝试使用:
req.on("close", function() {
console.log("client closed");
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
但没有运气。任何帮助将不胜感激。
But without luck. Any help will be appreciated.
推荐答案
浏览器关闭时不会向服务器发送http请求,我无法在Node.js文档中找不到有关请求对象上的close事件的任何内容。但是,我使用Socket.io设置了类似的东西。此示例每秒向客户端推送一个随机数,并在客户端断开连接后停止推送数据:
The browser won't send an http request to the server when it closes, and I couldn't find anything in the Node.js docs about a close event on the request object. However, I have set something up similar to this using Socket.io. This example pushes a random number to the client every second, and stops pushing data after the client disconnects:
io.on('connection', function(socket) {
var intervalID = setInterval(function () {
socket.emit('push', {randomNumber: Math.random()});
}, 1000);
socket.on('disconnect', function () {
clearInterval(intervalID);
});
}
以下是使用Express设置Socket.io 。
这篇关于即使客户端断开连接,Node.js服务器也会保留流数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!