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('https://: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>
現在,使用者需要建立一個 Node 應用程式,並使用以下命令安裝 ‘express’ 和 ‘cors’ NPM 包。
npm i express cors
之後,在 Node 應用程式中建立一個 server.js 檔案,並在檔案中新增以下程式碼。
在下面的程式碼中,我們建立了 ‘connect’ API 端點,它呼叫 manageClient() 函式。在 manageClient() 函式中,我們將必需的 header 新增到響應中。此外,我們將客戶端新增到響應中。
接下來,我們使用 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’ 事件已被觸發。
之後,當 ‘onmessage’ 事件觸發時,它會列印資料。使用者可以觀察下面的輸出。

使用者學習瞭如何在客戶端使用伺服器傳送事件的所有四個事件。第一個事件是 ‘open’,它確保連線已建立。第二個是 ‘message’ 事件,允許我們處理從伺服器獲取的資料。第三個事件是 ‘error’ 用於處理錯誤,最後一個事件是 ‘close’ 用於瞭解連線何時終止。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP