stg*_*123 7 api http node.js server-sent-events server
我正在 Firebase 中设置 Nodejs Express 服务器。我有一个仪表板页面。用户可以使用 Chrome 扩展程序随时将项目保存到仪表板。我希望他们新保存的项目定期出现在仪表板上。
繁忙的轮询似乎很容易运行
setInterval( () => {
// async call to api with paging cursor
Run Code Online (Sandbox Code Playgroud)
但这似乎是一种资源浪费。
我阅读了有关服务器端事件的信息并尝试用代码来实现它们。我见过的所有 SSE 示例都是这样的:
var clients = {}; // <- Keep a map of attached clients
app.get('/events/', function (req, res) {
req.socket.setTimeout(Number.MAX_VALUE);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
(function (clientId) {
clients[clientId] = res;
req.on("close", function () {
delete clients[clientId]
});
})(++clientId)
});
setInterval(function () {
var msg = Math.random();
console.log("Clients: " + Object.keys(clients) + " <- " + msg);
for (clientId in clients) {
clients[clientId].write("data: " + msg + "\n\n"); // <- Push a message to a single attached client
};
}, 2000);
Run Code Online (Sandbox Code Playgroud)
让 SSE 事件正常工作在测试示例中没有问题,并且它适用于我的用例。
然而,我的担忧是:
企业级应用程序如何真正实施有效的SSE?
| 归档时间: |
|
| 查看次数: |
596 次 |
| 最近记录: |