JavaScript 服务器发送事件有哪些事件可用
服务器发送事件允许开发人员在服务器和客户端之间打开一个连接,并从服务器向客户端发送数据。基本上,这是一种单向通信,这意味着我们可以从服务器向客户端发送数据,但不能从客户端向服务器发送数据。
在这里,我们将讨论JavaScript中可用的服务器发送事件的所有事件。
JavaScript中可用的服务器发送事件
JavaScript中共有4个不同的服务器发送事件可用。
- ‘onopen’ - 当客户端和服务器之间的连接成功建立时,’open’事件被触发。我们可以使用’open’事件来确保连接成功。
newEvent.onopen = () => {
// perform some action
}
- ‘onmessage’ − 每当服务器向客户端发送任何消息或数据时,触发‘message’事件。我们可以使用‘message’事件从服务器获取更新的数据,并在客户端上处理它。
newEvent.onmessage = message => {
// handle the message data
};
- ‘onerror’ - 每当在服务器和客户端连接时出现问题时,都会触发‘error’事件。我们可以使用‘error’事件来捕捉错误,并在每个时间间隔之后重试连接,直到成功建立连接为止。
newEvent.onerror = event => {
// handle error
}
- ‘onclose’ − ‘close’事件在客户端和服务器之间关闭连接时触发,无论是服务器还是客户端关闭连接。当‘close’事件触发时,我们可以清除浏览器缓存和其他数据。
newEvent.onclose = event => {
// clear the data
}
所有四个事件都可以在客户端使用。在这里,我们将通过以下示例来学习如何在客户端使用上述事件。
示例
首先,用户需要创建一个index.html文件,并将以下代码添加到其中。
在下面的示例中,我们使用EventSource()构造函数创建了”newEvent”对象。之后,我们将”onopen”事件添加到代码中,当它被触发时,打印一条简单的消息。
接下来,我们添加了”onmessage”事件,在客户端从服务器接收到消息时被触发,并在触发时处理数据。
文件名 – index.html
<html>
<body>
<h2>Using the <i> Server-sent events </i> for unidirectional communication in JavaScript.</h2>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
const newEvent = new EventSource('http://localhost:3000/connect');
// open event is fired when the connection is established.
newEvent.onopen = () => {
output.innerHTML += 'Connection to the server is successfully established. <br>';
}
// message event is fired when the server sends the data to the client.
newEvent.onmessage = message => {
output.innerHTML += "Updated message data is: " + message.data + "<br>";
};
// error event is fired when the connection is closed.
newEvent.onerror = event => {
output.innerHTML += `Error in the server-sent event: ${event}`;
}
// close event is fired when the connection is closed.
newEvent.onclose = event => {
output.innerHTML += 'Connection of the client with the server is closed.';
}
</script>
</body>
</html>
现在,用户需要创建一个节点应用程序,并通过以下命令安装 ‘express’ 和 ‘cors’ NPM 包。
npm i express cors
然后,在Node应用程序中创建一个server.js文件,并在文件中添加以下代码。
在以下代码中,我们创建了“connect”API端点,它调用manageClient()函数。在manageClient()函数中,我们向响应添加了一个必需的头部。此外,我们还将客户端添加到响应中。
接下来,我们使用for循环使用服务器发送的通知向客户端发送了5个更新。
const express = require("express");
const cors = require("cors");
const app = express();
// use cors
app.use(cors());
const PORT = 3000;
// array to store all connected clients
let clients = [];
// add the client to the list
async function manageClient(req, res) {
// set headers
const requiredHeaders = {
"Content-Type": "text/event-stream",
Connection: "keep-alive",
};
// adding 200 response code
res.writeHead(200, requiredHeaders);
// create a client object and add it to the list
const client = {
id: Math.random(),
res,
};
clients.push(client);
console.log(`Client is connected Successfully`);
for (let i = 0; i < 5; i++) {
// send data to the client
res.write(`data: test{i}
`);
}
}
// adding endpoints
app.get("/connect", manageClient);
// run the server
app.listen(PORT, () => {
console.log(`App listening on port{PORT}`);
});
使用以下命令运行Node应用程序的服务器。
node server.js
输出
当用户在浏览器中刷新index.html文件时,它建立了服务器和客户端之间的连接。此外,它打印出连接建立成功的消息,因为触发了’onopen’事件。
此后,当触发了’on message’事件时,它打印出数据。用户可以在下面观察输出结果。
用户学会了在客户端使用服务器发送事件的四个事件。第一个事件是’open’,确保连接已建立。第二个是’message’事件,允许我们处理从服务器获得的数据。第三个事件是’error’,用于处理错误,最后一个事件是’close’,用于了解连接何时被终止。