NodeJS 如何在我的express.js服务器上获得所有已建立的http-connections?

a14dhokn  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(79)

我在我的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`);


一些数组或集合来管理这个连接,但我不明白如何提取服务器上的每个唯一的已建立连接。

sulc1iza

sulc1iza1#

我认为这很简单,就像把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作为一个简单的数组可能不是最好的数据结构。

相关问题