乐闻世界logo
搜索文章和话题

EventSource 如何发送 SSE 事件?

4 个月前提问
2 个月前修改
浏览次数40

1个答案

1

EventSource 是一个浏览器内置的 API,用于创建到服务器的持久连接,以便服务器可以通过SSE(Server-Sent Events)协议发送事件。SSE 允许服务器端推送实时更新到客户端。

以下是服务器发送SSE事件的步骤:

1. 创建服务器端代码

服务器端需要有一个路由来处理SSE连接,并且能够发送事件。在 Node.js 中,这可能看起来像:

javascript
const express = require('express'); const app = express(); app.get('/events', function(req, res) { // 设置响应头以设置内容类型和允许CORS res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*', }); // 发送一个简单的事件 const id = Date.now(); res.write(`id: ${id}\n`); res.write("data: Hello, World!\n\n"); // 每隔一段时间发送一个新事件 const intervalId = setInterval(() => { const eventId = Date.now(); res.write(`id: ${eventId}\n`); res.write(`data: ${new Date().toLocaleTimeString()}\n\n`); }, 1000); // 当客户端断开连接时清除定时器 req.on('close', () => { clearInterval(intervalId); }); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

2. 创建客户端代码

在客户端,你需要创建一个 EventSource 的实例,并指定服务器端SSE路由的URL:

javascript
const evtSource = new EventSource('http://localhost:3000/events'); evtSource.onmessage = function(event) { console.log('New message:', event.data); }; evtSource.onopen = function(event) { console.log('Connection to server opened.'); }; evtSource.onerror = function(event) { console.error('EventSource failed.'); }; // 确保在不需要时关闭连接 window.onunload = function() { evtSource.close(); };

服务器通过持续的write操作将事件发送到客户端,而客户端通过事件监听来接收这些事件。服务器端发送的每个事件包括一个“data:”字段来传输消息内容,可选的“id:”来设置事件ID(这可以用于重连时的断点续传),以及“event:”字段来指定事件类型(如果未指定,则默认事件类型为"message")。

每个发送到客户端的消息都以两个换行符结束(\n\n),这是SSE协议规定的消息终止符。

通过以上步骤,我们可以实现一个基本的SSE通信。当然,在实际应用中,你可能还需要处理更复杂的场景,比如断线重连、用户认证、以及优化服务器端的资源管理等。

2024年6月29日 12:07 回复

你的答案