JavaScript 中的服务器发送事件是什么?
什么是 JavaScript 中的服务器发送事件?
在 JavaScript 中,服务器发送事件 (SSE) 使服务器能够向客户端发送数据。客户端需要与服务器建立连接以从服务器获取数据。
服务器发送事件类似于 WebSocket,因为它也建立了客户端和服务器之间的连接,并且可用于在双方发送数据。但是服务器发送事件允许单向通信,这意味着服务器可以向客户端发送数据,但客户端不能向服务器发送数据。
让我们构建一个使用服务器发送事件的实时 React 和 Node 应用程序。这里 React 是我们的前端,Node 是我们的后端。
示例
用户需要按照以下步骤使用实时应用程序中的服务器发送事件。
步骤 1 - 创建一个 React 应用程序。
步骤 2 - 在应用程序的项目目录中,运行以下命令以在项目中安装“axios”NPM 包。
npm i axios
步骤 3 - 在 App() 组件中,使用“useState”钩子更新我们从服务器接收到的消息。
步骤 3.1 - 使用 useEffect() 钩子在客户端和服务器之间建立连接。在这里,我们需要使用 EventSource() 构造函数通过传递服务器的 URL 来与服务器建立连接。
步骤 3.2 - 此外,在事件源上添加“message”事件监听器,每当客户端从服务器接收消息时,它都会调用 handleMessage() 函数。
步骤 3.3 - 接下来,创建一个对象,该对象删除“message”事件并关闭客户端和服务器之间的连接,并将其返回。
步骤 4 - 在 handleMessage() 函数中,获取我们从服务器接收到的数据,并将其推送到“messageData”钩子中。
步骤 5 - 添加一个 HTML 代码,显示我们从服务器接收到的所有消息。
步骤 5.1 - 添加“获取消息”按钮,该按钮调用“sendMessage()”函数。
步骤 5.2 - sendMessage() 函数从字符串数组中选择任何随机消息,并使用“axios”将其发送到服务器。服务器接收消息并通过服务器发送事件再次将其发送到客户端。
步骤 6 - 将以下代码添加到 app.js 文件中。
import React from "react";
import { useState, useEffect } from "react";
import axios from "axios";
const App = () => {
const [messageData, setMessageData] = useState([]);
useEffect(() => {
// add the client to the server
const newConnection = new EventSource("https://:5000/addClient");
newConnection.addEventListener("message", handleMessage);
return () => {
// close the event listener
newConnection.removeEventListener("message", handleMessage);
newConnection.close();
};
}, []);
// getting message from server
const handleMessage = (evt) => {
const eventData = JSON.parse(evt.data);
setMessageData((messages) => messages.concat(eventData));
};
// Send a random message to the server, which the server will send to the client via server-sent events
const sendMessage = () => {
let messages = [
"JavaScript",
"React",
"Node",
"Express",
"MongoDB",
"MySQL",
"Python",
"Django",
"Flask",
"Java",
"Spring",
"Spring Boot",
"Spring MVC",
"Spring Security",
"Spring Data",
];
const random = Math.floor(Math.random() * messages.length);
axios.post("https://:5000/message", {
message: messages[random],
});
};
return (
<div>
<h2> Server Sent Events </h2>
<div>
<h4> Click the below button to get a message from the server </h4>
<button onClick = {sendMessage}> Get message </button>
</div>
<div>
<h4> All messages </h4>
<p> Total messages: {messageData.length} </p>
{messageData.map((item, index) => (
<div key={index}> {item.message} </div>
))}
</div>
</div>
);
};
export default App;
步骤 7 - 使用以下命令运行服务器。
npm start
现在,用户需要创建一个 Node 应用程序来设置服务器。
步骤 8 - 在 Node 应用程序的项目目录中执行以下命令以安装 NPM 包。
npm i cors body-parser express
步骤 9 - 导入所需的 NPM 包并为应用程序设置服务器。
步骤 10 - 创建一个 API 端点以接收来自客户端的请求。
步骤 11 - 当服务器从“addClient”收到请求时,它将调用“addClient()”函数。
步骤 11.1 - 在 addClient() 函数内创建标头。之后,创建一个客户端对象,将 id 和“res”添加到其中,并推送到“allConnectedClients”数组中。
步骤 11.2 - 侦听“close”事件,并在服务器和客户端之间的内容结束时从“allConnectedClients”数组中删除客户端。
步骤 12 - 在 sendMessage() 函数中,从客户端获取消息并将其添加到“res”中。之后,调用 sendToClient() 函数,该函数通过服务器端事件将相同的消息发送到所有客户端。
步骤 13 - 将以下代码添加到 app.js 文件中。
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const PORT = 5000;
// array to store all connected clients
let allConnectedClients = [];
// add the client to the list
const addClient = (req, res) => {
// Set headers
const headers = {
"Content-Type": "text/event-stream",
Connection: "keep-alive",
};
// adding 200 response code
res.writeHead(200, headers);
// create a client object and add it to the list
const id = Date.now();
const client = {
id,
res,
};
allConnectedClients.push(client);
console.log(`Client is connected Successfully and its id is: ${id}`);
req.on("close", () => {
console.log(`Client is disconnected Successfully and its id is: ${id}`);
// remove the client from the list when it gets disconnected
allConnectedClients = allConnectedClients.filter(
(client) => client.id !== id
);
});
};
const sendToClient = (msg) => {
// iterate over all clients and send the message
allConnectedClients.forEach((singleClient) =>
singleClient.res.write(`data: ${JSON.stringify(msg)}
`)
);
};
const sendMessage = (req, res) => {
// Get the message from the request body
const msg = req.body;
// add message to response
res.json(msg);
return sendToClient(msg);
};
// use cors and body parser
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// adding endpoints
app.get("/addClient", addClient);
app.post("/message", sendMessage);
// run the server
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});
步骤 14 - 使用以下命令运行 Node 应用程序的代码。
node app.js
注意 - 用户需要确保服务器和客户端运行在不同的主机上,并且需要根据服务器的端口更改客户端中的 API 端点。
输出
当客户端成功连接时,用户将在 Node 应用程序的终端中看到以下输出。

对于前端部分,用户将看到以下输出。

上述应用程序的流程
成功运行两个服务器后,当用户打开前端部分时,它将请求“addClient”端点,该端点将在服务器和客户端之间建立连接。
之后,当用户单击“获取消息”按钮时,它将向“message”端点发送一个 POST 请求,并附带特定消息。服务器接收消息并通过服务器发送事件将其发送回客户端。
客户端接收消息,存储消息数据并在浏览器上显示。在这里,我们出于测试目的从客户端发送数据。但是,如果我们使用数据库并在数据库中更新任何数据,我们可以直接将更新的数据发送到服务器。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP