res.write()未立即结束事件



这段代码从今天起就不能正常工作,在今天之前,它在响应上工作得很好,所有的response.write((都在事件流上执行,但现在的问题是在api响应的response.writi((执行端。以及一次列出的所有事件。

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: countn');
res.write(`data: ${JSON.stringify({ count: count })}nn`);
if (count) setTimeout(() => countdown(res, id + 1, count - 1), 1000);
else res.end();
}
app.listen(3000, () => console.log('SSE app listening on port 3000!'));

在首页使用EventSource:

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

听起来这是一个"周期性地";问题您可以创建的连接数量是有限制的,尤其是当/如果协议是HTTP时(请参阅EventSource简介中的警告框(。

可以通过确保每次关闭/重新加载网页时都关闭连接来缓解这种情况。根据我的经验,浏览器最终会清理未使用的连接,但我不知道什么时候。

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

最新更新