WishMeLz

生活其实很有趣

SSE(Server-Sent Events)

服务端

const express = require("express");
const cors = require("cors");

const app = express();
const port = 6548;

app.use(cors());

app.get("/sse", (req, res) => {
  res.set({
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    Connection: "keep-alive",
  });

  res.flushHeaders();

  setInterval(() => {
    const data = {
      message: `Server time is ${new Date().toLocaleTimeString()}`,
    };

    res.write(`data: ${JSON.stringify(data)}\n\n`);
  }, 1000);
});

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

前端

 const events = document.getElementById("events");
      const source = new EventSource("http://127.0.0.1:6548/sse");
      source.onmessage = (event) => {
        const data = JSON.parse(event.data);
        const message = data.message;
        console.log(event);
     
      };