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 theclose()
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) { // 处理打开事件 };
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

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

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.

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

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

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

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.
