服务端推送技术Server-Sent Events(sse)

一、介绍

服务器发送事件(Server-Sent Events,简称SSE)是一种允许服务器主动向客户端(如网页浏览器)发送数据的技术。这通常用于创建实时或近乎实时的通信功能,如实时通知、聊天应用、股票行情更新等。SSE 是一种基于 HTTP 的技术,它只支持文本消息(通过 UTF-8 编码的文本)

二、使用场景

  1. 即时通讯
  2. 实时监控与告警
  3. 在线投票与问卷调查
  4. 实时博客评论与互动
  5. 实时位置跟踪
  6. 实时数据大屏

三、代码实现

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>

四、注意事项

  1. 安全性:SSE 通过 HTTP 发送,因此你应该通过 HTTPS 来确保数据传输的安全性。
  2. 浏览器兼容性:大多数现代浏览器都支持 SSE,但最好检查你的目标浏览器是否支持。
  3. 错误处理:在客户端和服务器端都应妥善处理可能的错误和异常。
  4. 资源清理:确保在不需要时关闭 EventSource 连接,以避免资源泄露

五、平替产品

@microsoft/fetch-event-source实现sse流式功能,fetch-event-source 是一个旨在提升浏览器端 Server-Sent Events (SSE) 体验的开源库,由微软提供并维护。

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值