1315 字
7 分钟
Server-Sent Events

简介#

Server-Sent Events (SSE) 是一种允许服务器向客户端推送实时数据的技术。它是基于 HTTP 的一种简单协议,使得服务器能够向客户端发送事件流,而无需客户端发起请求。这种技术在实时应用中非常有用,如股票行情、新闻更新等。 与WebSocket的区别是,WebSocket是双向的,而SSE是单向的流式输出。

工作原理#

SSE 的工作原理相对简单。服务器通过一个特殊的 HTTP 响应开始发送事件流。这个响应的 Content-Type 是 text/event-stream,并且可以持续不断地发送数据。客户端通过监听这个响应流,可以接收到服务器发送的事件。

客户端实现#

在客户端,SSE 通常通过 JavaScript 的 EventSource 对象实现。这个对象允许开发者监听服务器发送的事件。每当服务器发送新的数据,客户端的 EventSource 对象就会触发一个事件,开发者可以在这个事件的回调函数中处理数据。

var source = new EventSource('/events');
source.onmessage = function(event) {
console.log("Message from server: ", event.data);
};

服务器实现#

服务器端的实现则依赖于服务器的编程语言和框架。例如,在 Node.js 中,可以使用 sse 或 sse-server 这样的库来创建 SSE 服务器。服务器需要维护一个长连接,并且定期发送数据到这个连接。

优势#

  • 实时性:SSE 提供了一种简单直接的方式来实现实时数据传输。
  • 低延迟:由于不需要轮询,SSE 通常比传统的 AJAX 轮询有更低的延迟。
  • 易于实现:客户端和服务器端的实现都相对简单,不需要复杂的协议。

缺点#

  • 浏览器支持:虽然大多数现代浏览器支持 SSE,但仍然有一些老旧的浏览器不支持。
  • 服务器压力:对于高并发的实时应用,服务器可能会承受较大的压力。

结论#

Server-Sent Events 是一种强大的技术,它为开发者提供了一种简单的方式来实现实时数据流。随着浏览器和服务器端技术的进步,SSE 在实时应用中的使用将会越来越广泛。

使用Node实现SSE接口#

server.js
const http = require('node:http')
const fs = require('fs')
// https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html
// https://nodejs.cn/api/http.html#httpcreateserveroptions-requestlistener
const server = http.createServer((req, res) => {
// decodeURI 解码参数
const url = decodeURI(req.url)
if (url === '/' || url === 'index.html') {
// 如果请求根路径,返回 index.html 文件
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500)
res.end('Error loading')
} else {
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end(data)
}
})
} else if (url.includes('/sse')) {
// 如果请求 /sse 路径,建立 SSE 连接
// 写入响应头
res.writeHead(200, {
'Content-Type': 'text/event-stream', // 指定返回的数据类型为 text/event-stream
'Cache-Control': 'no-cache', // 禁用缓存
'Connection': 'keep-alive', // 保持连接
'Access-Control-Allow-Origin': '*', // 允许跨域
})
// 每隔 1 秒发送一条消息
let id = 0
const intervalId = setInterval(() => {
// event字段表示自定义的事件类型,默认是message事件。
res.write(`event: customEvent\n`)
// id字段表示消息编号,
res.write(`id: ${id}\n`)
// 指定浏览器重新发起连接的时间间隔。
res.write(`retry: 30000\n`)
// query参数转对象
const params = url.split('?')[1]
.split('&')
.map(item => item.split('='))
.reduce((prev, [key, value]) => ({ ...prev, [key]: value }), {})
const data = {
id,
time: new Date().toLocaleString(),
params
}
// data 携带的数据
res.write(`data: ${JSON.stringify(data)}\n\n`)
id++;
if (id >= 10) {
clearInterval(intervalId)
res.end()
}
}, 1000)
// 当客户端关闭连接时停止发送消息
req.on('close', () => {
clearInterval(intervalId)
id = 0
res.end()
})
} else {
// 如果请求的路径无效,返回 404 状态码
res.writeHead(404);
res.end()
}
})
server.listen(3000)
console.log('Server listening on : http://localhost:3000')

页面

index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SSE-demo</title>
</head>
<body>
<h1>SSE Demo</h1>
<button onclick="connectSSE()">建立SSE连接</button>
<button onclick="closeSSE()">断开SSE连接</button>
<div id="message"></div>
<script>
const msg = document.getElementById("message");
let eventSource = null;
const connectSSE = () => {
// https://developer.mozilla.org/zh-CN/docs/Web/API/Server-sent_events/Using_server-sent_events
eventSource = new EventSource("http://localhost:3000/sse?content=内容&hello=world");
// 监听消息事件 默认 onmessage 事件, eventSource.onmessage = e => { ... }
eventSource.addEventListener("customEvent", e => {
const data = JSON.parse(e.data);
// msg.innerHTML += `${data.id} -- ${data.time} -- ${JSON.stringify(data.params)}<br>`;
msg.innerHTML += `${e.data}<br>`;
});
eventSource.onopen = e => {
msg.innerHTML += "连接已建立<br>";
};
eventSource.onerror = e => {
msg.innerHTML += "连接发生错误<br>";
};
};
const closeSSE = () => {
eventSource.close();
msg.innerHTML += "连接已断开<br>";
};
</script>
</body>
</html>

使用node server.js启动服务端

在Apifox 中调试接口, 正常响应(当接口返回的 Content-Type 包含 text/event-stream 时,Apifox 会自动将返回的数据解析为 SSE 事件)

image-20240131172509444

或者直接访问: http://localhost:3000

image-20240131172626281

使用Koa做接口

'use strict';
const Koa = require("koa");
const { PassThrough } = require("stream");
const app = new Koa();
app.use(async (ctx) => {
ctx.status = 200;
ctx.set({
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream', // 表示返回数据是个 stream
});
const stream = new PassThrough();
ctx.body = stream;
sendSSE(stream, ctx);
});
app.listen(3000, () => {
console.log("main.js Server listening on : http://localhost:3000");
});
function sendSSE(stream, ctx) {
let id = 0;
const intervalId = setInterval(() => {
stream.write(`id: ${id}\n`);
stream.write(`retry: 30000\n`);
const data = {
id,
time: new Date().toLocaleString(),
params: ctx.query
};
stream.write(`data: ${JSON.stringify(data)}\n\n`);
id++;
if (id >= 10) {
clearInterval(intervalId);
stream.end();
}
}, 1000);
}

讯飞星火AI#

image-20240131174423524

阿里#

控制台中不能直接看到数据, 但是复制curl在apifox中重新请求可以

image-20240131175141301

image-20240131175310500

参考#

Server-Sent Events
https://blog.tiamix.cn/posts/server-sent-events/
作者
Tiam
发布于
2024-01-31
许可协议
CC BY-NC-SA 4.0