node如何使用sse通信
dearweb
发布:2023-03-27 21:12:02阅读:
在 Node.js 中,您可以使用 `EventSource` 对象来实现 SSE(Server-Sent Events)通信。下面是一个简单的示例:
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/sse') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// 发送 SSE 数据
setInterval(() => {
res.write(`data: ${new Date().toLocaleTimeString()}\n\n`);
}, 1000);
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`
<html>
<head>
<title>SSE Demo</title>
</head>
<body>
<h1>SSE Demo</h1>
<script>
const source = new EventSource('/sse');
source.onmessage = (event) => {
const data = event.data;
console.log(data);
};
</script>
</body>
</html>
`);
}
}).listen(3000);在此示例中,我们创建了一个 HTTP 服务器,并为 SSE 数据和 HTML 页面提供了不同的路由。当用户请求 `/sse` 路由时,我们将响应的 `Content-Type` 设置为 `text/event-stream`,这表示我们将发送 SSE 数据。然后,我们使用 `setInterval` 定期向客户端发送 SSE 数据。
在 HTML 页面中,我们使用 `EventSource` 对象来监听 `/sse` 路由的 SSE 数据。每当接收到 SSE 数据时,我们将其打印到控制台上。
希望这可以帮助您了解如何在 Node.js 中使用 SSE 通信。
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧