????????SSE(Server-Sent Events,服务器发送事件)是一种用于实现服务器端向客户端实时推送数据的技术。它允许服务器端发送任意数量的事件到客户端,而客户端可以通过EventSource API来订阅这些事件流。以下是关于SSE的相关概念:
1. 特点:
2. 使用:
//Node.js
const http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
setInterval(function() {
const randomNum = Math.floor(Math.random() * 100);
res.write(`data: ${randomNum}\n\n`);
}, 1000);
}).listen(3000);
//HTML/javaScript
<!DOCTYPE html>
<html>
<head>
<title>EventSource Example</title>
</head>
<body>
<div id="randomNumber"></div>
<script>
const eventSource = new EventSource('http://localhost:3000');
eventSource.onopen = function(event) {
document.getElementById('randomNumber').innerText = 'Random Number: ' + event.data;
};
eventSource.onmessage = function(event) {
};
eventSource.onerror = function(event) {
};
eventSource.onclose();
</script>
</body>
</html>
3. 注意事项:
4.参考与推荐: