我已经设置了一个简单的服务器发送事件来测试,它在客户端连接后定期发送数据。当客户端重新加载页面或移动到另一个页面时,浏览器关闭连接并停止接收事件。
app.get("/stream", (req, res) =>{
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
const data = JSON.parse(fs.readFileSync("./data/group_list.json"))
let i = 0;
const intervalId = setInterval(function() {
++i;
console.log('iteration', i);
if ( i === 5 ) {
clearInterval(intervalId);
res.end();
return 1
}
res.write('data:' + JSON.stringify(data) + '\n\n');
res.flush();
}, 3000);
})
这是我在React中的事件处理程序。
handleSSE = () => {
console.log('here');
const url = "/test/stream"
//url can be your server url
if ('EventSource' in window) {
let source = new EventSource(url)
source.onopen = (e) => console.log('cnx successful', e);
source.onmessage = (e) => console.log('data-', JSON.parse(e.data));
source.onerror = (e) => {
console.log('cnx failed', e);
source.close();
};
}
}
SSE只有在“i”达到某个数字时才停止发射数据,我希望SSE在客户端关闭连接时检测并停止发射数据。我特别需要的是我的服务器中的setInterval()在客户端关闭连接时停止的方法。
1条答案
按热度按时间kqlmhetl1#
我认为您需要在handleSSE函数中添加Windows卸载事件以检查连接。
为此,您需要在handleSSE函数中添加beforeunload的事件侦听器。
因此,最终的handleSSE函数将是: