node.js中的SSE不会触发“message listener”,直到res.end()。 原因是在代码或

请咨询一下。 客户代码:

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

并没有什么作品…但是如果我res.write()客户端触发alert()一次后, res.write()和服务器崩溃,因为它已经结束res 。 我读了这可能是防病毒的问题 ,我的客户端不会触发,直到连接closures,所以我closures防病毒,但没有帮助。 所以我的问题是:

  1. 是代码问题还是其他原因(防病毒)
  2. 如果是来自防病毒软件,是否为客户端防病毒或服务器的防病毒问题? (我正在使用Nod32防病毒软件在Windows上开发,如果我将在Linux上部署,它会有所帮助,还是取决于客户端的防病毒软件)
  3. 有没有其他select,但WebSocket(我只需要推动通知与最小的内存使用情况)

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

解决了

问题出在我使用的中间件“Compression”中

由于压缩的性质,这个模块不能和服务器发送的事件一起工作。 为了压缩内容,需要将输出的窗口缓冲起来以获得良好的压缩。 通常在使用服务器发送的事件时,有一定的数据块需要到达客户端。

你可以通过调用res.flush()来实现这一点,当你需要写入的数据实际上到客户端。