小编stg*_*123的帖子

如何存储SSE连接?

我正在 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) + …
Run Code Online (Sandbox Code Playgroud)

api http node.js server-sent-events server

7
推荐指数
0
解决办法
596
查看次数

标签 统计

api ×1

http ×1

node.js ×1

server ×1

server-sent-events ×1