一、介绍
服务器发送事件(Server-Sent Events,简称SSE)是一种允许服务器主动向客户端(如网页浏览器)发送数据的技术。这通常用于创建实时或近乎实时的通信功能,如实时通知、聊天应用、股票行情更新等。SSE 是一种基于 HTTP 的技术,它只支持文本消息(通过 UTF-8 编码的文本)
二、使用场景
- 即时通讯
- 实时监控与告警
- 在线投票与问卷调查
- 实时博客评论与互动
- 实时位置跟踪
- 实时数据大屏
三、代码实现
SSE一个简单的服务器端(以 Node.js 为例)和客户端(HTML + JavaScript)实现
node.jss实现
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// 模拟每秒发送一次消息
const interval = setInterval(() => {
const now = new Date();
const msg = `data: The server time is: ${now.toLocaleTimeString()}\n\n`;
res.write(msg);
}, 1000);
// 监听客户端断开连接
req.on('close', () => {
clearInterval(interval);
res.end();
});
} else {
res.writeHead(404);
res.end();
}
});
server.listen(8080, () => {
console.log('Server is running on http://localhost:8080');
});
客户端实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSE Example</title>
</head>
<body>
<h1>Server Time</h1>
<p id="time"></p>
<script>
const evtSource = new EventSource('/events');
evtSource.onmessage = function(e) {
const newElement = document.createElement("div");
newElement.textContent = "Server time update: " + e.data;
document.getElementById("time").appendChild(newElement);
};
evtSource.onerror = function(e) {
console.error('EventSource failed:', e);
evtSource.close();
};
</script>
</body>
</html>
四、注意事项
- 安全性:SSE 通过 HTTP 发送,因此你应该通过 HTTPS 来确保数据传输的安全性。
- 浏览器兼容性:大多数现代浏览器都支持 SSE,但最好检查你的目标浏览器是否支持。
- 错误处理:在客户端和服务器端都应妥善处理可能的错误和异常。
- 资源清理:确保在不需要时关闭
EventSource
连接,以避免资源泄露
五、平替产品
@microsoft/fetch-event-source实现sse流式功能,fetch-event-source 是一个旨在提升浏览器端 Server-Sent Events (SSE) 体验的开源库,由微软提供并维护。