简体   繁体   中英

res.write() not end event immediately

This code is not working proper since today, before today this is working well on response and all response.write() is execute on event-stream, but now problem is response.write() execute end of the api response. and all the event listed at a time.

const express = require('express');

const app = express();
app.use(express.static('public'));

app.get('/countdown', function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
    'Access-Control-Allow-Origin': '*'
  });
  countdown(res, 1, 10);
});

function countdown(res, id, count) {
  res.write(`id: ${id}\n`);
  res.write('event: count\n');
  res.write(`data: ${JSON.stringify({ count: count })}\n\n`);
  if (count) setTimeout(() => countdown(res, id + 1, count - 1), 1000);
  else res.end();
}

app.listen(3000, () => console.log('SSE app listening on port 3000!'));

And in your front page use EventSource:

<script>
  var source = new EventSource('http://localhost:3000/countdown');
  source.onmessage = function(event) {
    console.log(event);
  };
</script>

It sounds like this is a "periodically" issue. There is a limit to how many connections you can create, especially when/if the protocol is HTTP (see the warning box in the introduction of EventSource ).

This can be mitigated by ensuring that you close the connection each time that you close/reload the webpage. From my experience the browser will eventually clean up the unused connections, but I have no idea when.

var source = new EventSource('http://localhost:3000/countdown');

window.addEventListener('beforeunload', e => {
  // if the connection is not already closed, close it
  if(source.readyState != source.CLOSED){
    source.close();
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM