我在我的 Express 服务器应用程序上使用 SSE(服务器发送事件)来通知客户端一些事件。我的服务器上的代码:
sseRouter.get("/stream", (req, res) => {
sse.init(req, res);
});
let streamCount = 0;
class SSE extends EventEmitter {
constructor() {
super();
this.connections = [];
}
init(req, res) {
res.writeHead(200, {
Connection: "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
});
console.log("client connected init...");
this.connections.push(req); //?
let id = 0;
res.write(`data: some data \n\n`);
const dataListener = (data) => {
if (data.event) {
res.write(`event: ${data.event} \n`);
}
res.write(`event: ${data.data} \n`);
res.write(`id: ${++id} \n`);
res.write("\n");
};
this.on("data", dataListener);
req.on("close", () => {
this.removeListener("data", dataListener);
--streamCount;
console.log("Stream closed");
});
}};
使用此代码,我只能通过增加“streamCount”变量来计算连接总数,但我还需要保存来自客户端的每个已建立的http连接:
> eventSource = new EventSource(`${Constants.DEV_URL}/stream`);
某些数组或集合集合来管理此连接,但我无法理解如何提取服务器上每个唯一已建立的连接。
我认为这就像将
this.connections.push(req);
更改为: 一样简单
this.connections.push(res);
即可以随时使用
res
ponse 手柄来 write()
更多数据。因此,稍后将相同的 msg
发送给您可以做的每个人:
const msg = new Date().toISOString()
for(const res of this.connections)await res.write(`data:${msg}\n\n`);
您还需要一种方法在它们断开连接时删除它们的条目,或者您收到写入错误,因此
this.connections
作为简单数组可能不是最好的数据结构。