惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
Last Week in AI
Last Week in AI
月光博客
月光博客
D
DataBreaches.Net
WordPress大学
WordPress大学
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 叶小钗
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
Recent Announcements
Recent Announcements
宝玉的分享
宝玉的分享
MyScale Blog
MyScale Blog
C
Check Point Blog
F
Fortinet All Blogs
B
Blog
小众软件
小众软件
Vercel News
Vercel News
罗磊的独立博客
有赞技术团队
有赞技术团队

时间的朋友

Windows 命令行密码重置 Anaconda安装 typescript 注解解读1 Konvajs Shape加载自定义图片 sshpass 使用 why-is-node-running webgl笔记 SharedArrayBuffer is not defined blender 常用快捷键 | 时间的朋友 vue -- v3.4commit提交记录2 vue2 升级vue3报错问题整理 着色器 expressjs 源码 hyper-V arch linux 网络配置 element input数字格式化 three 拼接货架 WebAudio笔记 Windows nginx重启bat脚本 vue -- v3.4commit提交记录 URI malformed vue3 -- Class 对象在组件中使用范例 | 时间的朋友 ruby 安装和升级 element-plus 老版本cascader使用卡死问题 vue3 内置Transition组件 | 时间的朋友 前端memo的实现 | 时间的朋友 Vue -- vue-class-component源码 | 时间的朋友 linux 优化脚本 typescript 装饰器 | 时间的朋友 microbundle 源码 | 时间的朋友 WSL2问题解决WslRegisterDistribution failed with error: 0x800701bc
EventSource | 时间的朋友
2023-06-21 · via 时间的朋友

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
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>