Core points
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 handlerAfter 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.
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)
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!