服务器发送的事件:如何检测客户端与Node.js服务器的断开连接

i5desfxk  于 2023-02-08  发布在  Node.js
关注(0)|答案(1)|浏览(257)

我已经设置了一个简单的服务器发送事件来测试,它在客户端连接后定期发送数据。当客户端重新加载页面或移动到另一个页面时,浏览器关闭连接并停止接收事件。

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()在客户端关闭连接时停止的方法。

kqlmhetl

kqlmhetl1#

我认为您需要在handleSSE函数中添加Windows卸载事件以检查连接。
为此,您需要在handleSSE函数中添加beforeunload的事件侦听器。
因此,最终的handleSSE函数将是:

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();
    };
    window.addEventListener("beforeunload", () => {
      if (source.readyState !== EventSource.CLOSED) {
        source.close();
      }
    });
  }
}

相关问题