EventSource

Published: · LastMod: June 21, 2023 · 286 words

Eventsource单向服务端推送 🔗

单向服务端推送

服务端部分 🔗

服务端需要设置返回头

1
"Content-Type": "text/event-stream"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const { createReadStream, createWriteStream } = require("fs")
const { createServer } = require("http")

const sendInterval = 2000

createServer((req, res) => {
  if (req.url === "/") {
    return createReadStream("./index.html").pipe(res)
  }
  if (req.url.indexOf("/chat") == 0) {
    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      Connection: "keep-alive",
      "Cache-Control": "no-cache",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Credentials": "true",
    })

    setInterval(function () {
      writeServerSendEvent(res, new Date().toLocaleTimeString())
    }, sendInterval)

    writeServerSendEvent(res, new Date().toLocaleTimeString())
  }
}).listen(3011, () => {
  console.log("listening on http://localhost:3011")
})
function writeServerSendEvent(res, data) {
  res.write("data: " + data + "\n\n")
}

数据部分需要通过data:开头

1
data: message\n

如果是多行数据

1
2
data: line1\n
data: line2\n

如果是发送json数据

1
2
3
4
data: {\n
data: "msg": "hello world",\n
data: "id": 12345\n
data: }\n

前端部分 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <pre id="code"></pre>
    <script>

        const code = document.querySelector('#code')

        const source = new EventSource("http://localhost:3011/chat", {withCredentials: true});

        source.addEventListener("message", (e) => {
            code.innerHTML = e.data
        })

        source.addEventListener("error", () => {
            console.log('on error');
        })
    </script>
</body>
</html>