Home > Web Front-end > JS Tutorial > Creating real-time applications with SSE (Server-Sent events)

Creating real-time applications with SSE (Server-Sent events)

DDD
Release: 2025-01-28 08:31:12
Original
176 people have browsed it

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.

Criando aplicações em tempo real com SSE (Server-Sent Events)

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

Different from the traditional HTTP request (client issued a request, the server returns response), the SSE connection always keeps open to realize the one -way communication from the server to the client. Unlike the WebSocket that allows two -way communication, SSE only sends data to the client alone, and the client receives real time during the connection.

Criando aplicações em tempo real com SSE (Server-Sent Events) 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. Criando aplicações em tempo real com SSE (Server-Sent Events)

Connect the management system

In 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).

Application is a system that needs to enter Userid and establish a SSE connection. After that, the server sends an event every 5 seconds and returns a list of user lists. If the user offses the connection, it will be automatically removed from the connected user list.

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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

<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>
Copy after login
Copy after login
Back to the back end, create a connection.js file to manage the connection between the user and the server:

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): Criando aplicações em tempo real com SSE (Server-Sent Events)

<code class="language-bash">npm init -y
npm i express</code>
Copy after login
Copy after login

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>
Copy after login
Copy after login

Here are three points:

  1. /Events endpoints must respond to the client with Content-Type: text/event-stream head. This allows clients to identify SSE communication and create EventSource objects to establish connections.
  2. The server sends an event response to the connected client every five seconds to inform which users have established a connection.
  3. Using Event monitoring shutdown connection allows disconnected users to remove from the connection mapping. req.on("close", () => {})
The back end has been completed! Now you can pay attention to the front end.

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;
  • Two buttons: one for startup, the other is used to turn off the SSE connection;
  • A label, showing the user list that has been connected to, this list will update the events sent by the server.
  • <ul>
  • Then add js code to the script.js:
    <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>
    Copy after login
    Copy after login

    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>
    Copy after login
    Copy after login

    Criando aplicações em tempo real com SSE (Server-Sent Events)

    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.

    Criando aplicações em tempo real com SSE (Server-Sent Events) Please note that for integrity, I added error processing and some code details, such as adding

    checks in the

    function 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!

    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template