Node.js server keeps streaming data even after client disconnected

99封情书 提交于 2020-01-06 05:48:10

问题


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?

I tried to use:

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.


回答1:


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);
  });
}

Here's how you set up Socket.io with Express.



来源:https://stackoverflow.com/questions/29496634/node-js-server-keeps-streaming-data-even-after-client-disconnected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!