gpt4 book ai didi

node.js - 获取 SSE 消息、Angular 前端、Node 后端时出错

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:29 27 4
gpt4 key购买 nike

我正在使用 SSE 将简单消息从 Node 后端发送到 Angular 应用程序。到目前为止,它一直工作得完美无缺,但今天我意识到它不再工作了,而且我找不到原因。

这是相关代码:

Node

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

正如我所说,几周来一切都运行良好。今天我发现我没有收到任何消息,我一直在尝试找出原因,但运气不佳。

有什么线索可以说明问题吗?

最佳答案

最后,我找到了解决方案:

也许是因为更新了一些 Node 模块或 Node 本身,它添加了某种缓冲区来优化连接流量。为了使应用程序再次工作,我所要做的就是在每条消息后添加一个 flush ,如下所示:

[...]
res.write('data: ' + msgData + "\n\n");

// Send the message instantly
res.flush();
[...]

干杯,

关于node.js - 获取 SSE 消息、Angular 前端、Node 后端时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52002230/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com