SSE-based front-end data real-time updating method
The SSE-based method addresses inefficiencies in real-time data updates by establishing a long connection for real-time data delivery, reducing server load and enhancing user experience while supporting broad browser compatibility.
Patent Information
- Application Number
- CN202411245610.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-09-06
- Publication Date
- 2024-12-24
AI Technical Summary
Existing methods for real-time data updates, such as polling, long polling, and WebSockets, face inefficiencies in resource consumption, delay, and compatibility issues, failing to provide an optimal solution for real-time data push to clients.
Implementing a front-end data real-time updating method based on Server-Sent Events (SSE), which includes defining a controller to process SSE requests, creating an SseEmitter object to send data, establishing an SSE connection with an EventSource object, and using callback functions to manage data updates, thereby supporting real-time data delivery and reducing server load.
SSE reduces server load, improves performance, enhances user experience, and supports wide browser compatibility, offering a more efficient and real-time data push than traditional methods.
Smart Images

Figure CN119179574A_ABST
Abstract
Description
Technical Field
[0001] The invention relates to the technical field of computer communication, in particular to a front-end data real-time updating method based on SSE. Background Art
[0002] In daily development, we often encounter business scenarios where the server needs to actively push data to the client, such as real-time data on the data screen, unread messages in the message center, chat functions, etc.
[0003] Currently, the main solutions to achieve these requirements are polling / long polling and websocket.
[0004] Polling is a more traditional method. The client sends a request to the server at regular intervals to ask if there is any new data. The server only needs to check the data status and then return the result to the client. The advantages of polling are simple implementation and good compatibility; the disadvantages are that it may cause large delays and consume a lot of server resources. Long polling is an improved version of polling. The client sends a request to the server. After the server receives the request, if there is new data, it will immediately return it to the client; if there is no new data, the server will wait for a certain period of time (such as a 30-second timeout). During this period of time, if there is new data, it will be returned to the client, otherwise it will return empty data. After the client processes the response returned by the server, it will initiate a new request again, and so on. Compared with the traditional polling method, long polling reduces the number of requests, but there is still a certain delay.
[0005] Websocket is a two-way communication protocol. Its advantage is that it can support both the client and the server to communicate with each other. It is very powerful. The disadvantage is that Websocket is a new protocol WS / WSS, and browsers that support the HTTP protocol may not support the WS protocol. And because Websocket is more powerful, its structure is more complex and relatively heavy. Summary of the invention
[0006] The technical task of the present invention is to address the above deficiencies and provide a front-end data real-time update method based on SSE, which can realize real-time notification and enhance user experience; and can save resources, reduce server load and improve performance.
[0007] The technical solution adopted by the present invention to solve its technical problem is:
[0008] A front-end data real-time updating method based on SSE, the implementation of the method comprises the following steps:
[0009] 1) The backend defines a controller to process SSE requests and send real-time data;
[0010] 2) Create an SseEmitter object as an event emitter, obtain data through the interface or query database data, and convert the data into a string and send it to the client;
[0011] 3) The data sent by the emitter.send() method will be encapsulated in the form of an SSE event stream, and the client will receive the data in real time by listening to the event stream;
[0012] 4) The front end creates an EventSource object and establishes an SSE connection with the back end controller;
[0013] 5) Define a callback function for receiving data and update the data on the page when new data is received.
[0014] Based on SSE, appropriate server-side methods and front-end interfaces are established to replace the corresponding polling or websocket interfaces to update page data and message information, realize real-time notification and enhance user experience. SSE supports disconnection and reconnection by default, supports custom data types to be sent, saves resources, reduces server load and improves performance.
[0015] Furthermore, the step 1) is specifically implemented as follows:
[0016] Define a streamStockPrice() method, use the @GetMapping annotation to map the / stock-price path to this method, and specify produces = MediaType.TEXT_EVENT_STREAM_VALUE to indicate that this method will generate an SSE event stream;
[0017] Create an SseEmitter object as an event emitter within this method.
[0018] Furthermore, in step 4), the front end creates an EventSource object through new EventSource(' / stock-price'), which establishes an SSE connection with the / stock-price path.
[0019] Furthermore, the EventSource object receives two parameters: URL and options;
[0020] The URL is the source of the http event. Once the EventSource object is created, the browser immediately starts to listen to the events sent from the URL address.
[0021] options is an optional object that contains the withCredentials property, which indicates whether to send credentials (cookies, HTTP authentication information, etc.) to the server. The default value is false.
[0022] Furthermore, the EventSource object has a readyState property value:
[0023] 0, equivalent to the constant EventSource.CONNECTING, indicating that the connection has not been established or the connection is disconnected;
[0024] 1, equivalent to the constant EventSource.OPEN, indicating that the connection has been established and data can be received;
[0025] 2, which is equivalent to the constant EventSource.CLOSED, indicating that the connection is broken and will not be reconnected.
[0026] Furthermore, in step 5), the callback function for receiving data is defined through eventSource.onmessage. The EventSource object itself inherits from the EventTarget interface, so the addEventListener() method can be used to listen to events;
[0027] The events triggered by the EventSource object mainly include the following three types:
[0028] Open event: triggered when successfully connected to the server;
[0029] message event: triggered when a message sent by the server is received; the data attribute of the event object contains the content of the message sent by the server;
[0030] Error event: triggered when an error occurs; the event property of the event object contains the error information;
[0031] Or use attribute monitoring (onopen, onmessage, onerror) to only monitor predefined event types (open, message, error).
[0032] Furthermore, the backend establishes SseEmitterManger to uniformly manage the creation, release and data push of the current service SSE connection.
[0033] SseEmitterManger combined with Redis cache can manage SSE connections in a cluster environment, and can also be used with nginx, etc.
[0034] Furthermore, the entire link with the SSE connection interface enabled supports long connections.
[0035] The present invention also claims protection for a front-end data real-time update implementation device based on SSE, comprising: at least one memory and at least one processor;
[0036] The at least one memory is used to store a machine-readable program;
[0037] The at least one processor is used to call the machine-readable program to implement the above method.
[0038] The present invention also claims protection for a computer-readable medium having computer instructions stored thereon, which implement the above method when executed by a processor.
[0039] Compared with the prior art, the front-end data real-time updating method based on SSE of the present invention has the following beneficial effects:
[0040] The present invention provides a front-end real-time data update and message notification method based on SSE, establishes a long connection through TCP, reduces the number of TCP connections using the websocket interface, reduces the load of the server, improves performance, reduces complexity, reduces client consumption, has wide browser compatibility, and supports almost all browsers except IE. For browsers that do not support EventSource, polyfill can be used to implement it. Moreover, the method of using SSE is more efficient and real-time than the polling and long polling methods. BRIEF DESCRIPTION OF THE DRAWINGS
[0041] Figure 1 It is a flowchart of a front-end data real-time update method based on SSE provided in an embodiment of the present invention. DETAILED DESCRIPTION
[0042] The present invention will be further described below in conjunction with specific embodiments.
[0043] The embodiment of the present invention provides a front-end data real-time updating method based on SSE, and the implementation of the method includes the following steps:
[0044] 1. The backend defines a controller to process SSE requests and send real-time data;
[0045] Define a streamStockPrice() method, use the @GetMapping annotation to map the / stock-price path to this method, and specify produces = MediaType.TEXT_EVENT_STREAM_VALUE to indicate that this method will produce an SSE event stream.
[0046] 2. Create an SseEmitter object as an event emitter inside the method, obtain data through the interface or query database data, and convert the data into a string and send it to the client.
[0047] 3. The data sent by the emitter.send() method will be encapsulated in the form of an SSE event stream, and the client will receive data in real time by listening to the event stream.
[0048] 4. The front end creates an EventSource object through new EventSource(' / stock-price'), which establishes an SSE connection with the / stock-price path.
[0049] The EventSource object receives two parameters: URL and options.
[0050] The URL is the source of the http event. Once the EventSource object is created, the browser immediately starts to listen to the events sent from the URL address.
[0051] options is an optional object that contains the withCredentials property, which indicates whether to send credentials (cookies, HTTP authentication information, etc.) to the server. The default value is false.
[0052] The EventSource object has a readyState property with the following value:
[0053] 0, equivalent to the constant EventSource.CONNECTING, indicating that the connection has not been established or the connection is disconnected;
[0054] 1, equivalent to the constant EventSource.OPEN, indicating that the connection has been established and data can be received;
[0055] 2, which is equivalent to the constant EventSource.CLOSED, indicating that the connection is broken and will not be reconnected.
[0056] 5. Define the callback function for receiving data through eventSource.onmessage, and update the data on the page when new data is received.
[0057] The EventSource object itself inherits from the EventTarget interface, so you can use the addEventListener() method to listen for events. The events triggered by the EventSource object mainly include the following three types:
[0058] Open event: triggered when successfully connected to the server;
[0059] message event: triggered when a message sent by the server is received; the data attribute of the event object contains the content of the message sent by the server;
[0060] Error event: triggered when an error occurs; the event property of the event object contains the error information.
[0061] You can also use attribute monitoring (onopen, onmessage, onerror), which can only monitor predefined event types (open, message, error) and cannot be used to monitor custom event types.
[0062] The backend can also establish an SseEmitterManger to uniformly manage the creation, release, and data push of the current service SSE connection. Combined with Redis cache, the management of SSE connections in a cluster environment can be achieved, and it can also be used in conjunction with nginx, etc.
[0063] It should be noted that the entire link that enables the SSE connection interface must support long connections.
[0064] This method establishes appropriate server-side methods and front-end interfaces based on SSE to replace the corresponding polling or websocket interface to update page data and message information, realize real-time notification and enhance user experience. SSE supports disconnection and reconnection by default, supports custom data types to be sent, saves resources, reduces server load and improves performance.
[0065] SSE stands for Server-Sent Events. It is a web technology and a server-side push technology based on the HTTP protocol. It allows the server to send event streams to the client in a one-way manner. It is implemented through a standard HTTP connection and utilizes the long connection mechanism of HTTP. The client listens to the event stream on the server through the EventSource object to achieve real-time updates. SSE allows the server to push data to the client in real time. SSE is a communication-related API in the HTML5 specification. It mainly consists of two parts: the communication protocol between the server and the browser (based on the HTTP protocol), and the EventSource object that can be used by JavaScript on the browser. SSE runs on the HTTP protocol, which allows the server to send data to the client in the form of an event stream. The client can receive the data pushed by the server in real time by establishing a persistent HTTP connection and listening to this event stream.
[0066] WebSocket is a full-duplex communication protocol that allows two-way communication on a single TCP connection. Unlike the traditional HTTP request-response mode, after WebSocket establishes a connection, the client and server can maintain a long connection and send data to each other to achieve real-time communication. SSE is a one-way communication protocol and a long link. It can only support the server to actively push data to the client, but cannot allow the client to push messages to the server. Long connection is a persistent connection technology of HTTP / 1.1, which allows the client and server to make multiple HTTP requests and responses on a TCP connection without having to establish and disconnect a new connection for each request / response. Long connection helps reduce server load and improve performance. SSE is a lightweight protocol. Compared with websocket, its complexity is not that high and its consumption is relatively low compared to the client. Compared with traditional polling and long polling mechanisms, SSE provides a more efficient and real-time data push method. This technology is mainly used to build real-time applications.
[0067] This embodiment describes a front-end message real-time update method based on SSE. In SpringBoot, ResponseBodyEmitter or SseEmitter can be used to conveniently implement the SSE server. For front-end functions and pages that only need to display data, the SSE method can be used, and it can be used in combination with the websocket method that requires back-end operations.
[0068] The embodiment of the present invention also provides a device for implementing real-time update of front-end data based on SSE, comprising: at least one memory and at least one processor;
[0069] The at least one memory is used to store a machine-readable program;
[0070] The at least one processor is used to call the machine-readable program to implement the SSE-based front-end data real-time update method described in the above embodiment.
[0071] The embodiment of the present invention further provides a computer-readable medium, on which computer instructions are stored, and when the computer instructions are executed by a processor, the front-end data real-time update method based on SSE described in the above embodiment is implemented. Specifically, a system or device equipped with a storage medium can be provided, on which a software program code for implementing the functions of any of the above embodiments is stored, and a computer (or CPU or MPU) of the system or device reads and executes the program code stored in the storage medium.
[0072] In this case, the program code itself read from the storage medium can realize the function of any one of the above-mentioned embodiments, and thus the program code and the storage medium storing the program code constitute a part of the present invention.
[0073] The storage medium embodiments for providing the program code include a floppy disk, a hard disk, a magneto-optical disk, an optical disk (such as CD-ROM, CD-R, CD-RW, DVD-ROM, DVD-RAM, DVD-RW, DVD+RW), a magnetic tape, a non-volatile memory card, and a ROM. Alternatively, the program code can be downloaded from a server computer by a communication network.
[0074] In addition, it should be clear that the functions of any of the above embodiments can be implemented not only by executing the program code read by the computer, but also by enabling an operating system operating on the computer to complete part or all of the actual operations based on instructions from the program code.
[0075] In addition, it can be understood that the program code read from the storage medium is written to a memory provided in an expansion board inserted into the computer or written to a memory provided in an expansion unit connected to the computer, and then based on the instructions of the program code, a CPU installed on the expansion board or the expansion unit is enabled to perform part or all of the actual operations, thereby realizing the functions of any of the above-mentioned embodiments.
[0076] The present invention is shown and described in detail above through the accompanying drawings and preferred embodiments. However, the present invention is not limited to these disclosed embodiments. Based on the above multiple embodiments, those skilled in the art can know that the code review methods in the above different embodiments can be combined to obtain more embodiments of the present invention, and these embodiments are also within the protection scope of the present invention.
Claims
1. A front-end data real-time update method based on SSE, characterized in that: The implementation of this method includes the following steps: 1) The backend defines a controller to process SSE requests and send real-time data; 2) Create an SseEmitter object as an event emitter, obtain data through the interface or query database data, and convert the data into a string and send it to the client; 3) The data sent by the emitter.send() method will be encapsulated in the form of an SSE event stream, and the client will receive the data in real time by listening to the event stream; 4) The front end creates an EventSource object and establishes an SSE connection with the back end controller; 5) Define a callback function for receiving data and update the data on the page when new data is received.
2. A front-end data real-time updating method based on SSE according to claim 1, characterized in that: The step 1) is specifically implemented as follows: Define a streamStockPrice() method, use the @GetMapping annotation to map the / stock-price path to this method, and specify produces = MediaType.TEXT_EVENT_STREAM_VALUE to indicate that this method will generate an SSE event stream; Create an SseEmitter object as an event emitter within this method.
3. A front-end data real-time updating method based on SSE according to claim 2, characterized in that: In step 4), the front end creates an EventSource object through new EventSource(' / stock-price'), which establishes an SSE connection with the / stock-price path.
4. A front-end data real-time updating method based on SSE according to claim 1 or 3, characterized in that: The EventSource object receives two parameters: URL and options; The URL is the source of the http event. Once the EventSource object is created, the browser immediately starts to listen to the events sent from the URL address. options is an optional object that contains the withCredentials property, which indicates whether to send credentials to the server. The default value is false.
5. A front-end data real-time updating method based on SSE according to claim 4, characterized in that: The EventSource object has a readyState property value: 0, equivalent to the constant EventSource.CONNECTING, indicating that the connection has not been established or the connection is disconnected; 1, equivalent to the constant EventSource.OPEN, indicating that the connection has been established and data can be received; 2, which is equivalent to the constant EventSource.CLOSED, indicating that the connection is broken and will not be reconnected.
6. The method for real-time updating of front-end data based on SSE according to claim 1, characterized in that: In step 5), define a callback function for receiving data through eventSource.onmessage, and use the addEventListener() method to listen for events; The events triggered by the EventSource object include: Open event: triggered when successfully connected to the server; message event: triggered when a message sent by the server is received; the data attribute of the event object contains the content of the message sent by the server; Error event: triggered when an error occurs; the event property of the event object contains the error information; Or use property monitoring to monitor predefined event types.
7. The method for real-time updating of front-end data based on SSE according to claim 1, characterized in that: The backend establishes SseEmitterManger to uniformly manage the creation, release, and data push of the current service SSE connection.
8. The method for real-time updating of front-end data based on SSE according to claim 1, characterized in that: The entire link of the SSE connection interface supports long connection.
9. A device for implementing real-time update of front-end data based on SSE, characterized in that: include: at least one memory and at least one processor; The at least one memory is used to store a machine-readable program; The at least one processor is configured to call the machine-readable program to implement the method according to any one of claims 1 to 8.
10. A computer-readable medium, characterized in that The computer readable medium stores computer instructions, which, when executed by a processor, implement the method according to any one of claims 1 to 8.
