search
HomeWeb Front-endJS TutorialImplementing Push Technology Using Server-Sent Events

Implementing Push Technology Using Server-Sent Events

Core points

  • The Server-Sent Events (SSE) API implements push technology, and data is streamed to the client through continuous open connections, avoiding the overhead of repeatedly establishing new connections.
  • Unlike WebSockets that allow bidirectional communication, SSE only allows the server to push messages to the client. However, SSE has certain advantages, such as support for custom message types and automatic reconnection and disconnection.
  • Clients can handle various event types in the event stream by implementing named events. In addition, the onerror event handler of EventSource can be used to handle errors, and the client can terminate the EventSource connection at any time by calling the close() method.

Comparison with WebSockets

Many people are completely unaware of the existence of SSEs, as they are often obscured by the more powerful WebSockets API. Although WebSockets allows two-way full-duplex communication between the client and the server, SSE only allows the server to push messages to the client. Applications that require near-real-time performance or two-way communication may be more suitable for WebSockets. However, SSE also has some advantages over WebSockets. For example, SSE supports custom message types and automatic reconnection disconnection. These features can be implemented in WebSockets, but they are available by default in SSE. The WebSockets application also requires a server that supports the WebSockets protocol. In contrast, SSE is built on HTTP and can be implemented in a standard web server.

Detection support

SSE is relatively high in support, and Internet Explorer is the only major browser that does not support them yet. However, as long as IE lags behind, functional detection is still required. On the client, SSE uses the EventSource object to implement—a property of the global object. The following function detects whether the EventSource constructor is available in the browser. If the function returns true, SSE can be used. Otherwise, a backup mechanism such as polling should be used.

function supportsSSE() {
  return !!window.EventSource;
}

Connection

To connect to the event stream, call the EventSource constructor as shown below. You must specify the URL of the event stream to subscribe to. The constructor will automatically be responsible for opening the connection.

EventSource(url);

onopen Event handler

After establishing the connection, the onopen event handler of EventSource will be called. The event handler opens the event as its only parameter. The following example shows a common onopen event handler.

source.onopen = function(event) {
  // 处理打开事件
};
The

EventSource event handler can also be written using the addEventListener() method. This alternative syntax is better than onopen because it allows multiple handlers to be attached to the same event. The following uses addEventListener() to rewritten the previous onopen event handler.

source.addEventListener("open", function(event) {
  // 处理打开事件
}, false);

Receive message

The client interprets the event stream as a series of DOM message events. Each event received from the server triggers the onmessage event handler for EventSource. onmessage The handler takes the message event as its only parameter. The following example creates a onmessage event handler.

function supportsSSE() {
  return !!window.EventSource;
}

Message events contain three important properties - data, origin, and lastEventId. As the name implies, data contains the actual message data (string format). The data may be a JSON string and can be passed to the JSON.parse() method. The origin property contains the final URL of the event stream after any redirects. Origin should be checked to verify that messages are received only from the expected source. Finally, the lastEventId property contains the last message identifier seen in the event stream. The server can use this property to append an identifier to individual messages. If no identifier has been seen, lastEventId will be an empty string. The onmessage event handler can also be written using the addEventListener() method. The following example shows the addEventListener() event handler that was rewrited using onmessage.

EventSource(url);

Naming Event

By implementing Name event, a single event stream can specify various types of events. Named events are not handled by the message event handler. Instead, each type of naming event is handled by its own unique handler. For example, if the event stream contains an event named foo, the following event handler is required. Note that the foo event handler is the same as the message event handler, except that the event type is different. Of course, any other type of named messages requires a separate event handler.

source.onopen = function(event) {
  // 处理打开事件
};

Processing error

If there is a problem with the event flow, the onerror event handler for EventSource will be triggered. A common cause of errors is connection interruption. Although the EventSource object automatically tries to reconnect to the server, an error event will also be triggered when the connection is disconnected. The following example shows a onerror event handler.

source.addEventListener("open", function(event) {
  // 处理打开事件
}, false);

Of course, the onerror event handler can also be rewritten using addEventListener() as shown below.

source.onmessage = function(event) {
  var data = event.data;
  var origin = event.origin;
  var lastEventId = event.lastEventId;
  // 处理消息
};

Disconnect

The client can terminate the EventSource connection at any time by calling the close() method. The syntax of close() is shown below. The close() method does not accept any parameters and does not return any value.

source.addEventListener("message", function(event) {
  var data = event.data;
  var origin = event.origin;
  var lastEventId = event.lastEventId;
  // 处理消息
}, false);

Connection status

The status of the EventSource connection is stored in its readyState property. At any point in its life cycle, a connection can be in one of three possible states—in, ​​on, and off. The following list describes each state.

  • Connection – When an EventSource object is created, it will initially enter the connection state. During this period, the connection has not been established. If an established connection is lost, EventSource will also transition to the connection state. The readyState value of EventSocket in the connection is 0. This value is defined as the constant EventSource.CONNECTING.
  • Open – An established connection is called open. An EventSource object that is open can receive data. The readyState value of 1 corresponds to the open state. This value is defined as the constant EventSource.OPEN.
  • Close – If a connection is not established and a reconnection is not attempted, the EventSource is called closed. This state is usually entered by calling the close() method. The readyState value of the EventSource in a closed state is 2. This value is defined as the constant EventSource.CLOSED.

The following example shows how to check an EventSource connection using the readyState property. To avoid hard-coded readyState values, this example uses state constants.

function supportsSSE() {
  return !!window.EventSource;
}

Conclusion

This article introduces the client aspects of SSE. If you are interested in learning more about SSE, I recommend you read Server SSE. I also wrote a more practical article about SSE in Node.js. enjoy!

Frequently Asked Questions about Using SSE to Implement Push Technology (FAQ)

What are the prerequisites for implementing SSE?

To implement SSE, you need a basic understanding of JavaScript and Node.js. You should also be familiar with the concept of HTTP and how it works. Furthermore, understanding event-driven programming may be beneficial because SSE is based on this concept.

How is SSE different from WebSockets?

While both SSE and WebSockets provide real-time data updates, their capabilities and use cases vary. WebSockets provides a two-way communication channel between the client and the server, allowing both parties to send data at any time. On the other hand, SSE is a one-way communication channel where only the server can push updates to the client. This makes SSE more suitable for applications where data updates are primarily initiated by servers.

Can SSE be used with any server-side language?

Yes, SSE can be used with any HTTP-enabled server-side language. This includes languages ​​such as Node.js, Python, PHP, and Ruby. The key is to set the correct HTTP header and format the data according to the SSE specification.

How to deal with connection errors or interrupts in SSE?

The EventSource API used to implement SSE on the client will automatically attempt to reconnect to the server when the connection is lost. You can also listen for the "error" event on the EventSource object to manually handle connection errors or interrupts.

Can I use SSE to send data from the client to the server?

No, SSE is intended for one-way communication from the server to the client. If you need to send data from the client to the server, you can use traditional AJAX requests or switch to two-way communication technologies, such as WebSockets.

Does SSE support all browsers?

Most modern browsers support SSE. However, Internet Explorer does not support SSE. You can use polyfills like EventSource.js to add support for SSE in unsupported browsers.

How to close SSE connection?

You can close the SSE connection by calling the close() method on the EventSource object. This will prevent the server from sending more updates to the client.

Can I use SSE for multi-user real-time applications?

Yes, you can use SSE for multi-user real-time applications. However, remember that each user opens a separate connection to the server. If you have a large number of users, this can cause excessive server load.

How to use SSE to send different types of events?

You can send different types of events by including the "event" field in the data sent from the server. The client can then listen for these specific event types using the addEventListener() method on the EventSource object.

Can I use SSE with REST API?

Yes, you can use SSE with the REST API. The server can send updates to the client when the resource changes. This is useful for keeping the client and server state synchronized without polling.

The above is the detailed content of Implementing Push Technology Using Server-Sent Events. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use