我正在使用SSE将简单消息从Node后端发送到Angular应用程序。到目前为止,它一直在完美地工作,但今天我意识到它不再起作用了,我找不到原因。
这是相关代码:
节点
router.get('/stream', function (req, res) {
[ ... ]
// Send headers for event-stream connection
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
[ ... ]
// NOTE: This line connects to a Redis server
subscriber.subscribe(channel);
// In case we encounter an error...print it out to the console
subscriber.on("error", function (err) {
logger.debug("Redis Error: " + err);
});
// When we receive a message from the Redis connection
subscriber.on("message", function (channel, message) {
logger.debug('MESSAGE RECEIVED: ' + message); // This message is printed in the log file
[ ... ]
// Note: 'msgData' is obtained by parsing the received 'message'
// Send data to the client
res.write('data: ' + msgData + "\n\n");
});
}
角度应用
declare var EventSource : any;
getSSEMessages(): Observable<string> {
let sseUrl = `${ConfigService.settings.appURL}/stream`;
return new Observable<string>(obs => {
const es = new EventSource(sseUrl, { withCredentials: true });
// This prints '1' (CONNECTION OPEN)
console.log('SSE Connection: ', es.readyState);
// Note: I've also tried 'es.onerror'
es.addEventListener("error", (error) => {
console.log("Error in SSE connection", error);
return false;
});
// Note: I've also tried 'es.onmessage'
es.addEventListener("message", (evt : any) => {
// Never gets in here
console.log('SSE Message', evt.data);
obs.next(evt.data);
});
return () => es.close();
});
}
这是我在界面中选择选项时获取消息的方式:
this.getSSEMessages()
.subscribe(message => {
// SHOW MESSAGE TO THE USER
});
正如我所说,一切都运作良好数周。今天我看到我没有得到任何消息,我一直试图找出没有运气的原因。
什么可能是错的线索?
最后,我找到了一个解决方案:
也许是因为更新了一些Node模块或Node本身,它增加了一些缓冲区来优化连接流量。为了让应用程序再次运行,我所要做的就是在每条消息后添加一个flush
,如下所示:
[...]
res.write('data: ' + msgData + "\n\n");
// Send the message instantly
res.flush();
[...]
干杯,