Node.js server saves streaming data even after disconnecting the client

I have a small Node.js + express server that has a dummy loading 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 closing the browser, I still see that the node server is transmitting data. How to determine when a client is disconnected and stop streaming?

I tried using:

req.on("close", function() {
    console.log("client closed");
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

But no luck. Any help would be appreciated.

0
source share
1 answer

HTTP- , - Node.js . , - , Socket.io. :

io.on('connection', function(socket) {
  var intervalID = setInterval(function () {
    socket.emit('push', {randomNumber: Math.random()});
  }, 1000);
  socket.on('disconnect', function () {
    clearInterval(intervalID);
  });
}

Socket.io Express.

0

All Articles