Server-Sent Events (SSE) 实现从服务器到客户端的实时数据流

9a69fede8b2044a79dd834e3e48f20b4.png
前期回顾   

避免阻塞主线程 —— Web Worker 示例项目-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/m0_57904695/article/details/136721297?spm=1001.2014.3001.5501

目录

@CSDN 彩色之外

📝 前言

🛠️ 安装

✂️ 运行服务器

✂️ 运行index.html

♻️ 贡献


仓库点我👉及时推送到客户端消息

@CSDN 彩色之外

📝 前言

Server-Sent Events (SSE) 是什么?

Server-Sent Events (SSE) 是一种允许服务器主动向客户端发送更新的技术。与 WebSocket 不同,SSE 是单向通信,仅从服务器到客户端。这对于实时更新场景(如股票价格更新、新闻订阅、天气推送、每日笑话等)非常有用,而且实现起来比 WebSocket 简单。

 这个项目演示了如何使用 Server-Sent Events (SSE) 实现从服务器到客户端的实时数据流。它包括一个简单的 Node.js 服务器,使用 Express 框架设置 SSE 端点,以及一个 HTML 页面,通过 EventSource 接口接收来自服务器的消息。

 服务器每秒像客户端发送一次服务端生成的时间

 index.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>EventSource 示例</title>
</head>
<body>
    <h2>服务器发送的消息:</h2>
    <ul id="messages"></ul>
    <script>
        // 创建一个指向你的服务器端点的 EventSource 实例
        var eventSource = new EventSource('http://localhost:3000/events');
        // 使用 onmessage 事件监听器来接收消息
        eventSource.onmessage = function (event) {
            // 获取消息列表的元素
            var messagesElement = document.getElementById('messages');
            // 创建一个新的列表项元素,并设置其内容为接收到的消息
            var messageElement = document.createElement('li');
            messageElement.textContent = event.data;
            // 将新的列表项添加到消息列表中
            messagesElement.appendChild(messageElement);
        };
        // 监听错误事件
        eventSource.onerror = function (error) {
            console.error('EventSource failed:', error);
            // 在出现错误时关闭 EventSource
            eventSource.close();
        };
    </script>
</body>
</html>

server.js 

const express = require("express");
const cors = require("cors");
const app = express();
const PORT = 3000;
// 设置根URL的GET路由
app.get("/", (req, res) => {
	res.send(
		`<b>Hello, World!</b> - <br>使用 VS Code 的 Five Server<br> 1. 在 VS Code 中安装 Five Server 扩展。<br> 2. 与 Live Server 类似,重启 VS Code,打开你的项目文件夹。<br> 3. 找到你的 HTML 文件,右键点击并选择“Open with Five Server”。`
	);
});
// 允许跨域请求
app.use(cors());
app.get("/events", (req, res) => {
	res.setHeader("Content-Type", "text/event-stream");
	res.setHeader("Cache-Control", "no-cache");
	res.setHeader("Connection", "keep-alive");
	// 发送消息到客户端
	const sendMessage = () => {
		const data = `服务器时间: ${new Date()}`;
		res.write(`data: ${data}\n\n`);
		// 每秒发送一次
		setTimeout(sendMessage, 1000);
	};
	sendMessage();
});
app.listen(PORT, () => {
	console.log(`服务器运行在 http://localhost:${PORT}`);
});

🛠️ 安装

npm install express cors

✂️ 运行服务器

node server.js

> 在项目目录中,运行以上命令来启动服务器:

> 你将看到控制台输出,表明服务器已经在 http://localhost:3000 上运行。

 ✂️ 运行index.html

使用 VS Code 的 Five Server

1. 在 VS Code 中安装 Five Server 扩展。

2. 与 Live Server 类似,重启 VS Code,打开你的项目文件夹。

3. 找到你的 HTML 文件,右键点击并选择“Open with Five Server”。

 功能描述

   > 服务器 (server.js): 设置一个 SSE 端点 /events,每秒向客户端发送当前时间。

   > 客户端 (index.html): 使用 EventSource 接口连接到 SSE 端点,并在页面上显示接收到的消息。

   技术栈

   > Node.js: 服务器环境

   > Express: Node.js 的 web 应用框架,用于设置 SSE 端点。

   > CORS: 用于解决跨域请求的问题。

   > HTML/JavaScript: 客户端页面和逻辑。

♻️ 贡献

如果你有任何改进的建议或想要贡献代码,请随时创建 pull 请求或提交问题。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容