sse 服务器通知客户端

前后端通信

const http = require("http");
const { EventEmitter } = require("events");

// 创建一个事件发射器
const eventEmitter = new EventEmitter();

// SSE 客户端列表
const clients = {};

// SSE 路由处理函数
function sseHandler(req, res) {
  // 为客户端分配唯一的标识符
  const clientId = generateClientId();

  // 设置响应头
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    Connection: "keep-alive",
  });

  // 将客户端添加到列表中
  clients[clientId] = res;

  // 客户端断开连接时,从列表中移除
  req.on("close", () => {
    delete clients[clientId];
  });
}

// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
  if (req.url === "/sse") {
    sseHandler(req, res);
  } else {
    res.writeHead(404);
    res.end();
  }
});

// 启动服务器
server.listen(3000, () => {
  console.log("Server is running on port 3000");
});

// 在需要的时候发送消息给 SSE 客户端
function sendSSEMessage(clientId, data) {
  const client = clients[clientId];
  if (client) {
    client.write(`data: ${data}\n\n`);
  }
}

// 示例:给特定 SSE 客户端发送消息
const clientId = "unique-client-id"; // 根据实际情况分配一个唯一的标识符
const message = "Hello, SSE client!"; // 要发送的消息内容
sendSSEMessage(clientId, message);

// 生成唯一的客户端标识符
function generateClientId() {
  return Math.random().toString(36).substring(2, 10);
}
Last Updated:
Contributors: 刘荣杰