Server-sent events
SSE演示示例
HTML代码 sse.html 如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let url = 'http://127.0.0.1:8844/stream'
let source = new EventSource(url, { withCredentials: false })
source.onopen = function (event) {
console.log('链接已建立')
}
source.onmessage = function (event) {
let data = event.data
console.log(`收到数据 ${data}`)
}
source.onerror = function (event) {
console.log('发生错误了', event)
}
</script>
</body>
</html>
Node服务端代码如下:
var http = require("http");
http.createServer(function (req, res) {
var fileName = "." + req.url;
if (fileName === "./stream") {
res.writeHead(200, {
"Content-Type":"text/event-stream",
"Cache-Control":"no-cache",
"Connection":"keep-alive",
"Access-Control-Allow-Origin": 'http://127.0.0.1:5500',
});
res.write("retry: 10000\n");
res.write("event: connecttime\n");
res.write("data: " + (new Date()) + "\n\n");
res.write("data: " + (new Date()) + "\n\n");
let interval = setInterval(function () {
res.write("data: " + (new Date()) + "\n\n");
}, 1000);
req.connection.addListener("close", function () {
clearInterval(interval);
}, false);
}
}).listen(8844, "127.0.0.1");
**注意:**我使用的 VS Code 的 Open with Live Server 在 5500 端口打开的,你需根据自己的端口修改上面 Node 部分的 Access-Control-Allow-Origin 的值。
SSE的浏览器兼容性
除了 IE 外,基本都支持。