2024年09月18日 建站教程
Server-Sent Events(SSE)是一种使用HTTP协议向客户端发送实时事件的技术。与WebSocket不同,SSE是单向的,只能由服务器向客户端发送数据,但它仍然是一种非常适合推送实时数据的技术。
在Node.js中,可以使用sse或express-sse等模块实现SSE。这些模块还提供了一些方便的API来发送事件和维护连接。
具体实现代码如下:
const express = require('express');
const sse = require('express-sse');
const app = express();
app.use(express.static('public'));
const sseServer = new sse();
// send an initial message to the client when the connection is established
sseServer.send('Connected');
// handle SSE requests from the client
app.get('/sse', sseServer.init);
// send a message to all connected clients
sseServer.send('A new message has arrived!');
// close the connection to all connected clients
sseServer.close();
app.listen(8080, () => {
console.log('SSE server started on port 8080');
});
本文链接:http://so.lmcjl.com/news/13323/