我在我的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`);
型
一些数组或集合来管理这个连接,但我不明白如何提取服务器上的每个唯一的已建立连接。
1条答案
按热度按时间sulc1iza1#
我认为这很简单,就像把
this.connections.push(req);
变成:字符串
即.
res
ponse句柄可以在任何时候使用write()
更多的数据.所以以后发送相同的msg
给每个人,你可以做:型
你还需要一种方法在它们断开连接时删除它们的条目,或者你得到一个写错误,所以
this.connections
作为一个简单的数组可能不是最好的数据结构。