Ten years ago, if you need to develop real -time application (such as chat or update feed), the preferred plan is Polling. This technology sends the update data to the server by time and repeatedly sending HTTP requests. However, even if there is no new information, the request will still be sent, causing a waste of bandwidth and server processing capabilities.
Fortunately, the times change. Now using JavaScript, we can use the EventSource library to establish an SSE (server sending event) connection. This article will discuss the concept of SSE and provide a brief tutorial.
Live connection
After the connection is established, the data reaches the JavaScript client in the form of an event. There is no need to constantly request updates from the server as inquiries. The server is responsible for sending events containing updated data when necessary.
Unless the connection is closed, the client will continue to wait for the new data event sent by the server, which makes it an ideal technology that builds a notice that needs to be continuously updated, instrument panel or chat.
Connect the management systemIn order to practice the above concept, we will create a Node.js (back -end) application to provide the SSE connection endpoint for JavaScript client (front end).
Let's start!Create the index.js file, concentrate the back -end logic. In addition, create a/public folder to store index.html and script.js files to manage pages. The structure is as follows:
In Index.js, import the Express library (used to create http endpoints):
<code class="language-bash">npm init -y npm i express</code>
In /public/index.html, create a basic HTML to display the title and test whether the server runs:
<code>/public index.html script.js index.js package.json</code>
Now, running NPM Start in the terminal, the page should be displayed in the browser:
<code class="language-javascript">import express from "express" import fs from "fs" import path from "path" const app = express() app.use(express.json()) app.use(express.static(path.join(path.resolve(path.dirname("")), "public"))) app.get("/", (_, res) => { res.writeHead(200, { "content-language": "text/html" }) const streamIndexHtml = fs.createReadStream("index.html") streamIndexHtml.pipe(res) }) const PORT = 3000 app.listen(PORT, () => console.log(`Server is running on ${PORT} port`))</code>
<code class="language-html"><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Server Sent Events Demo</title> <h1>Server Sent Events Demo (SSE)</h1> </head> <body> </body> </html></code>
In it, export the Connection class, store the user mapping that has been connected to the user (registered new users) and the RemoveUSER method (remove the user from the mapping):
<code class="language-bash">npm init -y npm i express</code>
Since the Connection class isolated the connection management logic, we need to configure a endpoint in the server (index.js) so that the client can start SSE communication. These connections will be managed by the Connection class:
<code>/public index.html script.js index.js package.json</code>
Here are three points:
Content-Type: text/event-stream
head. This allows clients to identify SSE communication and create EventSource objects to establish connections. req.on("close", () => {})
Since the server has provided the SSE connection endpoint, the client needs to request this address and wait for the sending event.
In the index.html file, we will create:
<ul> A text field for users to enter userid;
<ul>
<code class="language-javascript">import express from "express" import fs from "fs" import path from "path" const app = express() app.use(express.json()) app.use(express.static(path.join(path.resolve(path.dirname("")), "public"))) app.get("/", (_, res) => { res.writeHead(200, { "content-language": "text/html" }) const streamIndexHtml = fs.createReadStream("index.html") streamIndexHtml.pipe(res) }) const PORT = 3000 app.listen(PORT, () => console.log(`Server is running on ${PORT} port`))</code>
Open the two tab pages in the browser to test the real -time connection to observe the update of the user.
<code class="language-html"><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Server Sent Events Demo</title> <h1>Server Sent Events Demo (SSE)</h1> </head> <body> </body> </html></code>
This completes a simple SSE real -time connection system. This technology is very suitable for the server to continue to send one -way data to the client, such as Feed, chat or instrument panel.
Please note that for integrity, I added error processing and some code details, such as adding
checks in thefunction and adding
event processing procedures to the function. These improvements enhance the robustness and reliability of the code. closeConnection
The above is the detailed content of Creating real-time applications with SSE (Server-Sent events). For more information, please follow other related articles on the PHP Chinese website!