node.js中的SSE直到res.end()才会触发“消息侦听器”.原因在代码中或

SSE in node.js doesn't fire "message listener" until res.end(). Reason is in code or

本文关键字:消息侦听器 侦听器 消息 代码 直到 SSE 中的 js res end node      更新时间:2023-09-26

>请提供一些建议。客户端代码:

var source = new EventSource('/notifications/stream');
    source.addEventListener('open', function(e) {
        console.log('SSE connected')
    }, false);
    source.addEventListener('message', function(e) {
        alert('yes')
        console.log('SSE connected')
    }, false);

服务器代码

// set timeout as high as possible
req.socket.setTimeout(Infinity);
// send headers for event-stream connection
// see spec for more information
res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
});

res.write(''n');
setInterval(function(){
  console.log('writing');
   res.write("id: " + Date.now()  + "'n");
    res.write("data: " + '{"message":"hello world"} ' + "'n'n");
}, 1000);

什么都没用...但是如果我在客户端触发alert()一次并且服务器崩溃后添加res.end() res.write()因为它已经结束了res.我读到可能是防病毒的问题,我的客户端在连接关闭之前不会触发,所以我关闭了防病毒软件,但它没有帮助。所以我的问题是:

  1. 是代码问题还是其他原因(防病毒(
  2. 如果它来自防病毒软件,是针对客户端防病毒还是服务器的防病毒问题?(我正在使用Nod32防病毒软件在Windows上开发,如果我在Linux上部署,它会有所帮助还是取决于客户端的防病毒软件(
  3. 除了 websocket 之外还有其他选择吗(我唯一需要的是以最小的内存使用量推送通知(

NodeJS 版本 0.10.28感谢您的关注。对不起,英语不好。

已解决

问题出在我在 express 中使用的中间件"压缩">

由于压缩的性质,此模块不能与服务器发送的事件一起开箱即用。要压缩内容,需要缓冲输出窗口以获得良好的压缩效果。通常,在使用服务器发送的事件时,需要到达客户端的某些数据块。

您可以通过调用 res.flush(( 来实现这一点,当你需要写入数据以实际将其提供给客户端时。