国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
onopen Event handler
What are the prerequisites for implementing SSE?
How is SSE different from WebSockets?
Can SSE be used with any server-side language?
How to deal with connection errors or interrupts in SSE?
Can I use SSE to send data from the client to the server?
Does SSE support all browsers?
How to close SSE connection?
Can I use SSE for multi-user real-time applications?
How to use SSE to send different types of events?
Can I use SSE with REST API?
Home Web Front-end JS Tutorial Implementing Push Technology Using Server-Sent Events

Implementing Push Technology Using Server-Sent Events

Feb 24, 2025 am 10:28 AM

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 Article

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)

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

What are best practices for writing clean and maintainable JavaScript code? What are best practices for writing clean and maintainable JavaScript code? Jun 23, 2025 am 12:35 AM

To write clean and maintainable JavaScript code, the following four points should be followed: 1. Use clear and consistent naming specifications, variable names are used with nouns such as count, function names are started with verbs such as fetchData(), and class names are used with PascalCase such as UserProfile; 2. Avoid excessively long functions and side effects, each function only does one thing, such as splitting update user information into formatUser, saveUser and renderUser; 3. Use modularity and componentization reasonably, such as splitting the page into UserProfile, UserStats and other widgets in React; 4. Write comments and documents until the time, focusing on explaining the key logic and algorithm selection

var vs let vs const: a quick JS roundup explainer var vs let vs const: a quick JS roundup explainer Jul 02, 2025 am 01:18 AM

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.

See all articles