我正在使用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");
});
}
Angular应用
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
});
就像我说的那样,几周来一切正常。今天我看到我没有收到任何消息,并且我一直在试图找出原因而没有运气。
关于什么是错误的任何线索?
答案 0 :(得分:0)
最后,我找到了解决方法:
也许是因为更新了某些Node模块或Node本身,所以添加了某种缓冲区来优化连接流量。为了使应用程序再次正常工作,我要做的就是在每条消息后添加一个position:absolute
,如下所示:
<div
id="test"
fxLayout="row"
fxLayoutGap="12px"
fxLayoutAlign="start center"
[class.hasFocus]="numberMatInput.value">
<mat-form-field appearance="outline">
<mat-label>KM</mat-label>
<input matInput #numberMatInput [formControl]="numberInput">
</mat-form-field>
</div>
干杯