Home Web Front-end JS Tutorial How Server-Sent Events (SSE) Work

How Server-Sent Events (SSE) Work

Sep 28, 2024 am 06:17 AM

How Server-Sent Events (SSE) Work

SSE (Server Sent Events) is not widely used in the world of web development, this article will take a deep dive into what SSE is, how it works, and how it can benefit your application.


What is SSE?

SSE is a simple and efficient way to send real-time updates from a server to a client over an HTTP connection. It is a part of the HTML5 specification and is supported by all modern web browsers. SSE is based on a unidirectional data flow, where the server sends messages to the client, but the client cannot send messages back to the server.

SSE uses a text-based format known as “Server-Sent Events” to send data to the client. The data is sent as a series of events, each of which contains a message and an optional event type. The event type is used to distinguish between different types of messages and allows the client to handle them differently.

How does SSE work?

The SSE protocol works by establishing a persistent HTTP connection between the server and the client. This connection is kept open for as long as the client wants to receive updates from the server. When the server has new data to send, it sends an HTTP response with a special MIME type “text/event-stream”.

The response contains a series of events, each of which is separated by a new line character (“n”). Each event has the following format:

event: [event type]\n
data: [message]\n\n
Copy after login

The “event” field is optional and is used to provide a name for the event. The “data” field contains the actual message being sent. The two newline characters at the end of each event are used to signal the end of the event.

Here’s an example of a simple SSE response:

HTTP/1.1 200 OK
Content-Type: text/event-stream

event: message
data: Hello, world!

event: message
data: This is a test message.

event: customEvent
data: {"foo": "bar", "baz": 123}
Copy after login

In this example, we’re sending three events to the client. The first two events have the event type “message” and contain simple text messages. The third event has the event type “customEvent” and contains a JSON object as its message.

When the client receives an SSE response, it uses the data to update its user interface. This can be done using JavaScript to manipulate the DOM, for example.

Implementing SSE

Implementing SSE in your application is relatively straightforward. Here’s an example of how to implement SSE using Node.js and the Express framework:

const express = require('express');
const app = express();

// Set up SSE endpoint
app.get('/events', (req, res) => {
  // Set headers
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  // Send initial event
  res.write('data: Connected\n\n');
  // Set interval to send periodic events
  const intervalId = setInterval(() => {
    res.write('data: Hello, world!\n\n');
  }, 1000);
  // Clean up on connection close
  req.on('close', () => {
    clearInterval(intervalId);
  });
});

// Start server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});
Copy after login

In this example, we’re setting up an SSE endpoint at “/events”. We’re setting the necessary headers for SSE and sending an initial event to the client to confirm that the connection has been established.

We’re then setting up an interval to send periodic events to the client every second. Finally, we’re cleaning up the interval when the connection is closed by the client.

On the client side, we can use the following JavaScript code to listen for SSE events:

const source = new EventSource('/events');

source.addEventListener('message', (event) => {
  console.log(event.data);
});
source.addEventListener('error', (event) => {
  console.error('Error:', event);
});
Copy after login

In this example, we’re creating a new EventSource object and passing in the URL of our SSE endpoint. We’re then listening for the “message” event and logging the data to the console. We’re also listening for the “error” event in case there are any connection issues.

Note that the EventSource path on the front end can only be used by GET requests, if you want to use POST and other HTTP methods, you need to parse the response data yourself.

If you want a native Node.js implementation, here’s one

Use cases for SSE

SSE can be used in a wide range of applications that require real-time updates. Here are a few examples:

  • Social media platforms: SSE can be used to provide real-time updates for social media platforms, such as notifications of new messages, comments, or likes.

  • Financial applications: SSE can be used to provide real-time updates for financial applications, such as stock prices, currency exchange rates, or news.

  • Online gaming: SSE can be used to provide real-time updates for online gaming applications, such as notifications of game events, scores, or rankings.

Benefits of using SSE

There are several benefits to using SSE over other real-time communication methods such as polling or WebSockets:

Efficiency

SSE uses a persistent HTTP connection, which means that the overhead of establishing and maintaining the connection is much lower than with other methods. This makes SSE more efficient and less resource-intensive, which is especially important when dealing with large numbers of clients.

Simplicity

SSE is a simple protocol that is easy to understand and implement. It does not require any special libraries or frameworks and can be implemented using standard web technologies such as JavaScript and HTTP.

Reliability

SSE is a reliable protocol that provides automatic reconnection in case of a network interruption. This ensures that the client will continue to receive updates even if the connection is temporarily lost.

Conclusion

Server-Sent Events (SSE) are a simple and efficient way to send real-time updates from a server to a client over an HTTP connection. It is a part of the HTML5 specification and is supported by all modern web browsers. SSE uses a unidirectional data flow, where the server sends messages to the client, but the client cannot send messages back to the server. This saves you from constantly polling the server for events, which not only improves performance but also reduces complexity.

If you found this helpful, please consider subscribing to my newsletter for more useful articles and tools about web development. Thanks for reading!

The above is the detailed content of How Server-Sent Events (SSE) Work. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles