ChatGPT流式输出实现原理

const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  if (req.url === "/events") {
    // 设置响应头,指明使用 text/event-stream 类型
    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
    });

    // 每隔一段时间向客户端发送一个 SSE 事件
    const intervalId = setInterval(() => {
      const data = JSON.stringify({ message: "This is a server-sent event." });
      res.write(`data: ${data}\n\n`);
    }, 1000);

    // 当客户端关闭连接时清除定时器
    req.on("close", () => {
      clearInterval(intervalId);
    });
  } else {
    res.writeHead(200, { "Content-Type": "text/html" });
    // 返回一个包含 SSE 客户端的 HTML 页面
    const html = fs.readFileSync("sse-client.html", "utf8");
    res.end(html);
  }
});

server.listen(8008, () => {
  console.log("Server is running on port 8000");
});
<!DOCTYPE html>
<html>

<head>
    <title>SSE Client</title>
</head>

<body>
    <script>
        const eventSource = new EventSource('/events');
        eventSource.onmessage = function (event) {
            console.log('Received event:', event.data);
        };
    </script>
</body>

</html>
posted @ 2023-11-14 16:29  古德拉克  阅读(146)  评论(0编辑  收藏  举报