A client communication method, a storage medium and a client
By listening to browser tab events and sending status notification messages, combined with reconnection mechanisms and heartbeat frequency adjustments, the problem of WebSocket connections disconnecting in the browser background is solved, enabling rapid communication recovery, adapting to the browser's energy-saving mechanisms, and reducing resource waste.
Patent Information
- Application Number
- CN202611405453.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-10
- Publication Date
- 2026-11-20
AI Technical Summary
Existing WebSocket connections are prone to prolonged heartbeats due to browser power-saving mechanisms when running in the browser background, causing the server to misjudge the connection as abnormal and disconnect it, thus failing to achieve effective bidirectional real-time communication.
By listening to browser tab switching events and sending browser status notification messages, the system can promptly detect and rebuild connections. Combined with a preset reconnection mechanism and heartbeat frequency adjustment, it ensures rapid restoration of communication when the browser is activated.
It effectively reduces the risk of WebSocket connection disconnection, ensures rapid restoration of communication capabilities after browser activation, adapts to browser power-saving mechanisms, and reduces resource waste and user waiting time.
Smart Images

Figure CN123145295A_ABST
Abstract
Description
Technical Field
[0001] This article relates to computer communication network technology, and in particular to a client communication method, storage medium and client. Background Technology
[0002] In the early days, clients typically used polling or Comet techniques to obtain messages from servers. Polling involves the client sending an HTTP request to the server every few seconds, and the server responding with a message after receiving the request. This method requires the client to continuously send HTTP requests to the server, wasting bandwidth resources. Furthermore, HTTP requests can only be initiated by the client; the server cannot send requests to the client, making it not true real-time communication. Comet technology includes long polling and streaming methods. These two methods are improvements on polling, reducing unnecessary requests. Both are still based on a request-response model, and each request and response wastes bandwidth on the same header information, consuming significant server bandwidth and resources.
[0003] To enable bidirectional real-time communication between clients and servers and improve bandwidth utilization, the WebSocket protocol was developed in 2008. WebSocket is a protocol for full-duplex communication over a single TCP connection, allowing persistent connections between clients and servers to achieve real-time bidirectional data transmission. The WebSocket handshake phase uses the HTTP protocol; after a successful handshake, the connection is upgraded from HTTP to WebSocket, abandoning the HTTP request-response model. After years of development, the WebSocket protocol is supported by various browsers, and in 2011, RFC 6455 recognized it as an international standard.
[0004] The main differences between HTTP and WebSocket communication protocols are as follows: The HTTP protocol supports short connections, which are closed immediately after each request-response; the WebSocket protocol supports long connections, which can maintain the connection after a successful handshake, allowing multiple bidirectional communications between the client and the server.
[0005] The HTTP protocol is a half-duplex communication protocol, where the client must send a request before the server can respond; the WebSocket protocol supports full-duplex communication, where the client and server can send data simultaneously and independently.
[0006] However, existing WebSocket instances cannot handle WebSocket connection drops effectively. Because browsers implement JavaScript execution throttling and timer frequency reduction mechanisms for inactive (background) tabs, the actual execution interval of application-layer heartbeat tasks scheduled by client-side scripts running within those tabs (such as WebSocket send() operations triggered periodically based on setInterval / setTimeout) is extended. When this actual interval exceeds the server's preset heartbeat timeout threshold, the server determines the connection is abnormal because it has not received keep-alive information within the agreed time, thus triggering the WebSocket connection to close. Summary of the Invention
[0007] This application provides a client communication method, storage medium, and client that can reduce the risk of WebSocket connections being disconnected.
[0008] The client communication method provided in this application includes: After the login operation is performed, a business connection is established with the server based on the WebSocket protocol; Listen for browser tab switching events, including switching from an active state to an inactive state or switching from an inactive state to an active state. Upon detecting that the browser tab has switched from an active state to an inactive state, a notification message that the browser tab is in an inactive state is sent to the server based on the service connection. When the browser tab is detected to switch from an inactive state to an active state, the status of the service connection is checked. If the service connection is disconnected, the service connection is rebuilt based on the reconnection mechanism, and a notification message that the browser tab is in an active state is sent to the server after successful reconstruction.
[0009] The computer-readable storage medium provided in the embodiments of this application stores one or more programs, which can be executed by one or more processors to implement the client communication method as described in the embodiments of this application.
[0010] The client provided in this application embodiment includes: A storage module is configured to store computer program instructions that can be executed on a processor; The processing module is configured to execute the computer program instructions to implement the client communication method as described in the embodiments of this application.
[0011] The technical solution described in this application transforms the uncontrollable external factor of "browser background throttling" into a controllable state negotiation signal between the client and the server. When a browser tab is detected switching from active to inactive, an inactive notification message is sent to the server via the existing service connection. This allows the server to clearly know, before any heartbeat anomalies, that the connection has entered a restricted background mode; the subsequent extended heartbeat interval is due to the browser's power-saving mechanism, not a network failure or client crash, providing support for differentiated keep-alive strategies. When a browser service is detected switching from inactive to active, if the service connection is detected to be broken, a reconnection mechanism is directly initiated instead of waiting for the next service trigger or heartbeat timeout. This ensures that the user can restore communication capabilities in the shortest possible time after switching back to the browser tab.
[0012] Other features and advantages of this application will be set forth in the following description, and will be apparent in part from the description, or may be learned by practicing the application. Other advantages of this application can be realized and obtained by means of the embodiments described in the description and the accompanying drawings. Attached Figure Description
[0013] The accompanying drawings are used to provide an understanding of the technical solutions of this application and constitute a part of the specification. They are used together with the embodiments of this application to explain the technical solutions of this application and do not constitute a limitation on the technical solutions of this application.
[0014] Figure 1 A flowchart of a client communication method provided in an embodiment of this application; Figure 2 This is a schematic diagram of the client component modules provided in an embodiment of this application; Figure 3 This application provides an example of an event registry publishing / subscription graph. Figure 4 Example diagram of a client communication method based on the WebSocket protocol provided in this application embodiment; Figure 5 This is a diagram of the client-side components provided in an embodiment of this application. Detailed Implementation
[0015] This application describes several embodiments, but these descriptions are exemplary and not limiting, and it will be apparent to those skilled in the art that many more embodiments and implementations are possible within the scope of the embodiments described herein. Although many possible combinations of features are shown in the drawings and discussed in the detailed description, many other combinations of the disclosed features are also possible. Unless specifically limited, any feature or element of any embodiment may be used in combination with, or may replace, any feature or element of any other embodiment.
[0016] This application includes and contemplates combinations of features and elements known to those skilled in the art. The embodiments, features, and elements disclosed in this application can also be combined with any conventional features or elements to form unique inventive solutions. Any feature or element of any embodiment can also be combined with features or elements from other inventive solutions to form another unique inventive solution. Therefore, it should be understood that any feature shown and / or discussed in this application can be implemented individually or in any suitable combination. Therefore, the embodiments are not limited except by the limitations imposed by the appended claims and their equivalents. Furthermore, various modifications and changes can be made within the scope of the appended claims.
[0017] Furthermore, in describing representative embodiments, the specification may have presented methods and / or processes as a specific sequence of steps. However, the method or process should not be limited to the specific order of steps described herein, to the extent that it does not depend on such a specific order. As will be understood by those skilled in the art, other sequences of steps are also possible. Therefore, the specific order of steps set forth in the specification should not be construed as a limitation of the claims. Moreover, the claims concerning the method and / or process should not be limited to the steps performed in the written order, and those skilled in the art will readily understand that these orders can be varied and still remain within the spirit and scope of the embodiments of this application.
[0018] This application provides a client communication method, such as... Figure 1 As shown, the method includes: Step S101: After performing the login operation, a business connection is established with the server based on the WebSocket protocol; Step S102: Listen for browser tab switching events, including switching from an active state to an inactive state or switching from an inactive state to an active state. Step S103: Upon detecting that the browser tab has switched from an active state to an inactive state, a notification message that the browser tab is in an inactive state is sent to the server based on the service connection. Step S104: When the browser tab is detected to switch from an inactive state to an active state, the status of the service connection is checked. If the status of the service connection is disconnected, the service connection is rebuilt based on the reconnection mechanism, and a notification message that the browser tab is in an active state is sent to the server after successful reconstruction.
[0019] The technical solution described in this application transforms the uncontrollable external factor of "browser background throttling" into a controllable state negotiation signal between the client and the server. When a browser tab is detected switching from active to inactive, an inactive notification message is sent to the server via the existing service connection. This allows the server to clearly know, before any heartbeat anomalies, that the connection has entered a restricted background mode; the subsequent extended heartbeat interval is due to the browser's power-saving mechanism, not a network failure or client crash, providing support for differentiated keep-alive strategies. When a browser service is detected switching from inactive to active, if the service connection is detected to be broken, a reconnection mechanism is directly initiated instead of waiting for the next service trigger or heartbeat timeout. This ensures that the user can restore communication capabilities in the shortest possible time after switching back to the browser tab.
[0020] In an exemplary embodiment, rebuilding the service connection based on the reconnection mechanism includes: Perform a reconnection operation; After each reconnection operation, the number of connections is incremented by 1, and the status of the service connection is checked. If the status of the service connection remains disconnected, it is determined whether the number of connections has reached the preset number of reconnections. If the preset number of reconnections has been reached, a notification to disconnect the service connection is sent to the server to confirm that the reconstruction has failed. If the preset number of reconnections has not been reached, the process returns to the step of performing the reconnection operation. If the status of the service connection is "connected", then the reconstruction is considered successful.
[0021] The preset number of reconnections is the circuit breaker threshold in the reconnection mechanism. If there is no limit to reconnections, the client will continuously create TCP connections, perform TLS handshakes, and send HTTP Upgrade requests when the network is unreachable. This will cause the client's memory usage to continue to rise, and network bandwidth will be wasted (a large number of failed handshake packets occupy the channel). Therefore, this application embodiment sets a preset number of reconnections to maintain a balance between "trying to restore the connection" and "avoiding resource waste".
[0022] In an exemplary embodiment, to avoid the network being impacted by concentrated reconnection operations, a reconnection interval can be set in the reconnection operation. That is, before performing the reconnection operation, it is determined whether a preset reconnection interval has been reached. If it has been reached, the reconnection operation is then performed.
[0023] In an exemplary embodiment, the method for detecting the status of the service connection may include: detecting the status of the service connection by sending a heartbeat packet; if a response to the heartbeat packet is received from the server within a preset heartbeat timeout window, it indicates that the service connection is normal; if no response to the heartbeat packet is received from the server within the preset heartbeat timeout window, it indicates that the service connection is abnormal, and a heartbeat packet retransmission mechanism can be triggered; if no response to the heartbeat packet is received from the server within the preset heartbeat timeout window after retransmission, it indicates that the service connection has been disconnected. The service connection is a long-lived connection between the client and the server established based on the WebSocket protocol, and the heartbeat packet is an application-layer keep-alive message transmitted through this long-lived connection.
[0024] In one exemplary embodiment, the method further includes: When the browser tab is detected to switch from an active state to an inactive state, a heartbeat packet is sent to the server at a first preset frequency; when the browser tab is detected to switch from an inactive state to an active state, a heartbeat packet is sent to the server at a second preset frequency; the first preset frequency is less than the second preset frequency.
[0025] The solution described in this application reduces the frequency of heartbeat packets sent to the server when a browser tab switches from an active to an inactive state. This adapts to the browser's energy-saving mechanism, reducing the risk of the tab being forcibly frozen / discarded by the browser, and reducing the client's power and bandwidth consumption. Conversely, increasing the frequency of heartbeat packets sent to the server when a browser tab switches from an inactive to an active state allows for rapid verification of whether the current service connection is still active. If the service connection has been silently disconnected, a high-frequency heartbeat can trigger a timeout determination as early as possible, thus quickly initiating the reconnection process and reducing unnecessary waiting for users operating in the foreground. Furthermore, sending heartbeat signals at different frequencies when the browser tab is active or inactive can further help the server determine whether the connection has entered a restricted background mode.
[0026] In one exemplary embodiment, the method further includes: After detecting the status of the service connection, if the service connection is connected, a notification message that the browser tab is active is sent directly to the server.
[0027] In one exemplary embodiment, the method further includes: After establishing a business connection with the server based on the WebSocket protocol, the system receives topic subscription messages pushed by the server based on the business connection, including: Upon receiving a Topic subscription message pushed by the server, the Topic field in the message is extracted. The system checks whether there exists a callback result set in the set callback pool that maps to the Topic field and processes messages containing that Topic field. If a corresponding callback result set exists, the Topic subscription message is processed using that callback result set. If no corresponding callback result set exists, a mapping relationship is established in the callback pool between the Topic field and the callback result set that processes messages containing that Topic field.
[0028] The callback collection pool refers to a data structure maintained in the client's memory for storing and managing the "Topic-callback function" mapping relationship; the callback result set refers to the collection of callback functions (processing logic) and their associated contexts used to process the corresponding Topic messages.
[0029] If all Topic callback functions that might be used by business modules are statically pre-registered at the initial stage of connection establishment (after onOpen), given the large number of Topic types but the fact that only a few Topics are triggered in actual sessions, a large number of pre-registered callback functions will occupy memory for a long time, slowing down the initialization speed. The technical solution described in this application dynamically establishes the mapping relationship between Topic fields and the callback result set that processes messages with that Topic field only when the message first actually arrives. This ensures that untriggered Topics do not occupy any resources in the callback set pool, significantly reducing client memory usage, avoiding invalid resource resident, and improving connection initialization speed and page response performance.
[0030] In one exemplary embodiment, the method further includes: Upon receiving a Topic subscription message pushed by the server, before performing the check to see if a callback result set containing messages with that Topic field exists in the configured callback pool, the message identifier ID is extracted from the Topic subscription message. A unique identifier, `receiveMessageId`, is generated based on this ID and sent to the server for message matching. After receiving confirmation of a successful match from the server, the check to see if a callback result set containing messages with that Topic field exists in the configured callback pool is then performed. For example, the server can use this ID as the key to search in the message matching connection pool maintained by the server; if a corresponding ID is found, the match is successful; otherwise, the match is unsuccessful.
[0031] Considering that the client directly queries the callback pool and performs processing upon receiving a message, if the message is a network replay, expired delivery, forged or tampered message, or a residual message after session expiration, it may cause the callback pool to be erroneously triggered, resulting in the execution of business logic; the client may be illegally driven, leading to data corruption; and the client may suffer from invalid calculations and resource waste, etc. In this embodiment, server matching confirmation is used as a pre-gate for callback execution. Only after the server confirms a successful match will the client be allowed to query the callback pool, which can prevent illegal or expired messages from polluting the client's business layer from the source.
[0032] In one exemplary embodiment, the method further includes: During the process of receiving the Topic subscription message pushed by the server based on the business connection, an error event handling method is used to capture error information; the captured error information is compared with the connection state readyState recorded internally by the WebSocket protocol; if the error information is consistent with the readyState, the state of the business connection is changed.
[0033] For example, if the error message indicates that the connection layer has failed and is consistent with the closed / closing state displayed by readyState, then it is confirmed that the connection has been substantially broken. The application layer will synchronously change the business connection state to "disconnected / awaiting reconnection" to prevent the client from mistakenly believing that the connection is still alive and continuing to send invalid data. If the error message indicates a momentary abnormality in the transport layer, but readyState is still OPEN, then it is determined to be a recoverable error. The business connection state does not need to be changed immediately to avoid unnecessary disconnection and reconstruction of the still reusable connection.
[0034] The technical solution described in this embodiment can prevent the application layer state from becoming disconnected from the actual state of the protocol layer, and eliminate two-way misjudgments such as "the protocol layer is dead but the business layer is still considered alive" or "the protocol layer is still available but the business layer has been incorrectly reset".
[0035] In one exemplary embodiment, the method further includes: After the logout operation is performed, the mapping relationship in the callback collection pool is removed.
[0036] In certain application scenarios, such as Single-Page Applications (SPAs), the client instance may not be destroyed after logging out (e.g., only switching routes or resetting state), and may subsequently be logged in again by the same device and client process (or even switching accounts). If the callback pool is not cleared, the residual Topic-callback mappings from the old session may conflict with the subscription requirements of the new session, causing the new user to receive push messages from the old user's subscribed topic; multiple different versions of callbacks may be registered for the same topic, leading to logic races. Clearing the mapping relationships in the callback pool ensures complete isolation of session state, allowing each login to establish a business subscription based on a clean initial environment. In addition, it can release client memory resources and avoid session-level memory leaks.
[0037] The following is an application example of a client communication method based on the WebSocket protocol.
[0038] like Figure 2 As shown, the client executing the client communication method based on the WebSocket protocol includes a WebSocket communication protocol module, a browser event (visibilitychange) module, and a publish-subscribe registry (registerEvents) module.
[0039] The WebSocket communication protocol module is configured to be responsible for real-time bidirectional data transmission between the client and server based on the TCP connection protocol, including the following methods: opening the connection channel (onOpen), heartbeat mechanism (heartbeat), reconnect mechanism (reconnect), exception handling mechanism (onError), sending mechanism (send), receiving mechanism (onMessage), event closing mechanism (onClose), and event destruction mechanism (onDestroy).
[0040] The browser event (visibilitychange) module is configured to listen for the switching states of various tabs in the browser, including methods such as event listening, event destruction, tab state (visibilityState), and Topic events. The tab state includes either an active state or an inactive state. The event listening is configured to listen for browser tab switching events, which include switching from an active state to an inactive state or vice versa. The Topic event is configured to use the listened-for tab switching state as a Topic event; for example, when a tab switches from an active state to an inactive state, the corresponding Topic event is {topic:”inactive”,content:{type:”system”}; when a tab switches from an inactive state to an active state, the corresponding Topic event is {topic:”active”,content:{type:”system”}. The Topic event is sent by the send mechanism in the WebSocket communication protocol module.
[0041] The publish / subscribe registry is configured with a convention for handling message interactions between clients and servers, including methods such as event registration (registerEvents) and a configuration center pool. When a client receives a message carrying a Topic from the server (publisher), it calls the registerEvents(topic, callback) method to pass the message to subscribers of the corresponding Topic via a callback function (stored in a callback collection pool). The callback message carries the Topic type. The configuration center pool is used to configure the callback collection pool. Figure 3 This illustrates a publish-subscribe graph for an event registry.
[0042] Client communication methods based on the WebSocket protocol include: After the login operation is performed, a connection is established based on the WebSocket server address; a WebSocket object is instantiated using the `new` method (`new WebSocket (wss: / / xxx)`); the `onOpen` method is used to determine whether the WebSocket connection has been successfully established and initialize the connection status (`readyStatus`); after confirming a successful connection, the initial connection status (`readyStatus`) is checked again to see if it is in a ready-to-work state; the first heartbeat detection method is performed; if the WebSocket application instance exists, the first message is sent to the server address; the system activation status event to be sent is set, and Topic message dispatch is used. The specific format of the sent content is as follows: send({ topic:'active', content:{ type: 'system' Tips: 'Active Status' } }) After successfully sending a message using the `send` method, the client uses the `onMessage` method to receive messages sent from the server. Upon receiving the message, the client extracts the message identifier ID, sends a new `receive` system message carrying a unique identifier `receiveMessageId` generated based on the message identifier ID, and sends it to the server's message matching connection pool for message matching. Once a successful match is confirmed from the server, the client extracts the Topic field from the message and checks if a callback result set exists in the set callback pool that maps to the Topic field and processes messages with that Topic. If a corresponding callback result set exists, it is used to process the Topic subscription message. If no corresponding callback result set exists, the `onCallback` method associates the result set executed for that Topic.
[0043] Furthermore, when the actual server frequently sends different topics, the message receiver may experience connection failures due to external factors, such as server service failures or insufficient browser storage space. In response to these situations, the onError method can be used to capture error information in a timely manner. Inside onError, the captured error information is compared with the connection state readyState recorded in the WebSocket protocol. If the error information matches the readyState, the state of the business connection is changed.
[0044] This application also supports a WebSocket reconnection mechanism, executing the `reconnect` method when a reconnection is triggered. The `reconnect` method allows you to set the reconnection interval, the number of reconnections, and a connection switch. Based on the set connection switch `lockReconnect`, it checks if the connection was successful; if not, it will attempt to connect. Based on the set number of reconnections `reconnectNumber`, it avoids excessive connection attempts; when the preset number of reconnections is reached, the connection is closed, and the server is notified to disconnect. The client executes the `onClose` method to close the local connection. Based on the set reconnection interval, it prevents connections from being concentrated in one area.
[0045] After the logout operation is performed, the connected state is closed by the onClose event and destroyed by the onDestroy event. During the destruction phase, the parameters of the WebSocket configuration center (reconnection count, reconnection timer, reconnection switch, heartbeat duration, event callback pool, etc.) are cleared, and the WebSocket initialization phase is restored.
[0046] Figure 4 This diagram illustrates an example of a client communication method based on the WebSocket protocol. It shows a closed-loop WebSocket message processing flow with reconnection fault tolerance, message type validation, and parsing filtering mechanisms.
[0047] First, determine whether the WebSocket connection, login, and initialization (init) have been completed: If the condition is not met: enter the reconnection mechanism and check if the number of reconnections exceeds 5. If it exceeds 5, filter the message and end the process; if it does not exceed 5, return to recheck the connection status.
[0048] If the following conditions are met: send a topic event and proceed to the server message receiving phase. During the server message receiving phase, first determine the message type: if it is not a valid message type, the process ends. If it is a valid message type, proceed with message parsing and dispatch.
[0049] This application embodiment can implement the client communication method based on the WebSocket protocol by using a socketInstance instance, including basic construction by the socketContext configuration center, including the data registration init method, createSocketInstance to initialize the connection, initialize data onParse, registerEvent event registration, and on event listening.
[0050] The data registration init method is configured with the server address and port, the unique token value for user login, heartbeat time, number of reconnections, and reconnection time. Different configuration information will be dynamically distributed to different business modules. The `createSocketInstance` initialization is configured to integrate and allocate parameter set values from the `socketContext` configuration center, requiring `socketInstance` initialization during this process. To prevent data contamination between different modules and to coordinate the connection status of different modules, each process (WebSocket object creation, channel connection, message reception, closure, and exception listening) can be attached by detecting the application instance's WebSocket. When the configuration center socketContext starts working, it initializes the data in onParse for messages sent by the server, converting them into the data format required by the business module through JSON.parse(data). This operation is mainly to standardize the data source and uniformly execute Object type objects. The `registerEvent` method is configured to bind the event name and message body of each Topic sent by the client, similar to a Map structure with key-value pairs. When a Topic event is detected through the `on` method, the corresponding callback event can be invoked via the `socketContext` configuration.
[0051] To implement the client communication method based on the WebSocket protocol described in the embodiments of this application, the technologies involved mainly include: Set up an instance configuration center based on WebSocket, including a parameter configuration module, providing heartbeat detection packets (status, interval duration, timer), reconnection mechanism (reconnection count, reconnection interval, timer, status), connection status, and also supporting custom configuration of server address and port; Build a WebSocket-based framework, install the SDK transport module information using an npm package, establish a connection and communication with WebSocket, and bind the server and port to the basic framework after the SDK transport module has finished processing. The client's SDK instance is introduced, and the connection between the client and the server is established through the SDK instance. The connection between the server and the client is first established based on the TCP protocol. During data transmission, the client will periodically send heartbeat packets to ensure the connection is active. If no heartbeat packet is received within a preset time, the server will actively disconnect the connection. The client will then reconnect. Introducing the publish-subscribe pattern: including designing topic collections and callback functions; During communication, WebSocket can transmit resources such as images, text, and attachments to the server in the form of streams or text. The server stores these resources based on the Topic passed by the client, so that the Topic name is carried as a unique identifier for a class of messages when the next message is dispatched. When the server actively pushes a message event, the client uses a publish-subscribe pattern based on the Topic event to detect the existence of the event. Messages sent by the server to the client are first sent to WebSocket, and WebSocket forwards the message to the client for rendering after receiving it. The activity state of browser tabs is detected by listening to browser visibilitychange events, primarily based on the tab the user is currently interacting with (e.g., mouse dragging, key presses, tab switching). When a browser tab switching event is detected, it can also check whether it conforms to a preset security mechanism policy. If not, the operation is stopped immediately; if it does, it determines what type of switching event occurred. When switching from inactive to active, the server and client communicate normally. The client sends Topic message commands to the server, and the publish-subscribe pattern parses the content distribution action set for the message commands to complete the message content adaptation. The publish-subscribe pattern records all Topic commands. When the client receives each message related to a Topic command, it triggers the publish-subscribe pattern to process the current message, and then renders the content of the current message on the corresponding page on the client. When switching from active to inactive, the browser will activate a power-saving mechanism, which will affect the duration of heartbeat sending. This may cause the server to be unable to receive messages sent by the client within a fixed period of time, thus causing the server to actively disconnect. After the disconnection, the client will initiate a reconnection mechanism. If all reconnections fail, the corresponding socketInstance instance will execute the close event to destroy data, disconnect the websocket connection, and wait for the user to activate the tab before reconnecting. The WebSocket connection status is dynamically adjusted based on the activity status of the tab and user behavior.
[0052] This application also provides a computer-readable storage medium storing one or more programs that can be executed by one or more processors to implement the methods described in any embodiment of this application.
[0053] This application also provides a client, such as... Figure 5 As shown, the client includes: Storage module 501 is configured to store computer program instructions that can be executed on a processor; The processing module 502 is configured to execute the computer program instructions to implement the method as described in any embodiment of this application.
[0054] It will be understood by those skilled in the art that all or some of the steps, systems, or apparatuses disclosed above, and their functional modules / units, can be implemented as software, firmware, hardware, or suitable combinations thereof. In hardware implementations, the division between functional modules / units mentioned above does not necessarily correspond to the division of physical components; for example, a physical component may have multiple functions, or a function or step may be performed collaboratively by several physical components. Some or all components may be implemented as software executed by a processor, such as a digital signal processor or microprocessor, or as hardware, or as an integrated circuit, such as an application-specific integrated circuit (ASIC). Such software may be distributed on a computer-readable medium, which may include computer storage media (or non-transitory media) and communication media (or transient media). As is known to those skilled in the art, the term "computer storage medium" includes volatile and non-volatile, removable and non-removable media implemented in any method or technology for storing information (such as computer-readable instructions, data structures, program modules, or other data). Computer storage media include, but are not limited to, RAM, ROM, EEPROM, flash memory or other memory technologies, CD-ROM, digital versatile disc (DVD) or other optical disc storage, magnetic cartridges, magnetic tape, disk storage or other magnetic storage devices, or any other medium that can be used to store desired information and can be accessed by a computer. Furthermore, it is well known to those skilled in the art that communication media typically contain computer-readable instructions, data structures, program modules, or other data in modulated data signals such as carrier waves or other transmission mechanisms, and may include any information delivery medium.
Claims
1. A client communication method, the method comprising: After the login operation is performed, a business connection is established with the server based on the WebSocket protocol; Listen for browser tab switching events, including switching from an active state to an inactive state or switching from an inactive state to an active state. Upon detecting that the browser tab has switched from an active state to an inactive state, a notification message that the browser tab is in an inactive state is sent to the server based on the service connection. When the browser tab is detected to switch from an inactive state to an active state, the status of the service connection is checked. If the service connection is disconnected, the service connection is rebuilt based on the reconnection mechanism, and a notification message that the browser tab is in an active state is sent to the server after successful reconstruction.
2. The method according to claim 1, characterized in that, The process of rebuilding the service connection based on the reconnection mechanism includes: Perform a reconnection operation; After each reconnection operation, the number of connections is incremented by 1, and the status of the service connection is checked. If the status of the service connection remains disconnected, it is determined whether the number of connections has reached the preset number of reconnections. If the preset number of reconnections has been reached, a notification to disconnect the service connection is sent to the server to confirm that the reconstruction has failed. If the preset number of reconnections has not been reached, the process returns to the step of performing the reconnection operation. If the status of the service connection is "connected", then the reconstruction is considered successful.
3. The method according to claim 1, characterized in that, The method further includes: When the browser tab is detected to switch from an active state to an inactive state, a heartbeat packet is sent to the server at a first preset frequency. When the browser tab is detected to switch from an inactive state to an active state, a heartbeat packet is sent to the server at a second preset frequency. The first preset frequency is less than the second preset frequency.
4. The method according to claim 1, characterized in that, The method further includes: After detecting the status of the service connection, if the service connection is connected, a notification message that the browser tab is active is sent directly to the server.
5. The method according to claim 1, characterized in that, The method further includes: After establishing a business connection with the server based on the WebSocket protocol, the system receives topic subscription messages pushed by the server based on the business connection, including: Upon receiving a Topic subscription message pushed by the server, extract the Topic field from the message and check if there is a callback result set in the set callback collection pool that has a mapping relationship with the Topic field and processes messages with the Topic field. If a corresponding callback result set exists, the subscription messages for the topic are processed using the corresponding callback result set; If no corresponding callback result set exists, a mapping relationship is established in the callback set pool between the Topic field and the callback result set that processes messages with the Topic field.
6. The method according to claim 5, characterized in that, The method further includes: Upon receiving a Topic subscription message pushed by the server, before executing the check to see if there is a callback result set in the callback pool that has a mapping relationship with the Topic field, the message identifier ID is extracted from the Topic subscription message, and a unique identifier receiveMessageId is generated based on the message identifier ID and sent to the server for message matching. After receiving confirmation from the server that a match is successful, the check to see if there is a callback result set in the callback pool that has a mapping relationship with the Topic field is then executed.
7. The method according to claim 6, characterized in that, The method further includes: During the process of receiving the Topic subscription message pushed by the server based on the business connection, error information is captured using an error event handling method. The captured error information is compared with the connection state readyState recorded internally by the WebSocket protocol. If the error information matches the readyState, the state of the business connection is changed.
8. The method according to claim 5, characterized in that, The method further includes: After the logout operation is performed, the mapping relationship in the callback collection pool is removed.
9. A computer-readable storage medium storing one or more programs that can be executed by one or more processors to implement the method as described in any one of claims 1 to 8.
10. A client, characterized in that, The client includes: A storage module is configured to store computer program instructions that can be executed on a processor; The processing module is configured to execute the computer program instructions to implement the method as described in any one of claims 1 to 8.
