A cross-terminal WebSocket long connection management method, system, device and medium

CN122994364APending Publication Date: 2026-10-27INSPUR INTELLIGENT NUMBER (TIANJIN) DIGITAL TECHNOLOGY CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611451344.3
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-09-18
Publication Date
2026-10-27

AI Technical Summary

Technical Problem

现有技术中,各业务模块或页面通常自行实现重连逻辑,由于缺乏统一的断线检测标准和重连调度机制,在网络频繁抖动时,多个模块可能同时发起重连请求,大量请求集中发送至服务端形成重连风暴;而在网络长期离线时,又因缺乏持续的重连恢复能力,导致连接在网络恢复后无法及时重建

Benefits of technology

本申请提供的跨端WebSocket长连接管理方法中,通过对WebSocket长连接从配置、建连、事件绑定、心跳保活到重连调度及订阅分发的全流程统一处理,使该方法在不同运行端差异下能够保证连接行为的一致性与稳定性,显著降低了多端接入的复杂度和维护成本,同时通过状态机协调、双通道事件绑定与多级去重、心跳保活与指数退避重连等机制,有效保障了长连接的可靠性、活性与业务接入的便捷性,为多端实时通知推送场景提供了一套统一、高效、可扩展的基础技术方案。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122994364A_ABST
    Figure CN122994364A_ABST
Patent Text Reader

Abstract

The application provides a cross-terminal WebSocket long connection management method, system, device and medium, and belongs to the technical field of network communication. The method comprises the following steps: uniformly configuring connection parameters of different terminals and constructing a connection URL; initiating connection according to the standardized configuration and the connection URL, coordinating the return order of opening events and task objects; registering events in a dual-channel mode of local event binding as the main mode and global event interface as the auxiliary mode according to the connection task object and the connection identifier, and obtaining standardized events after deduplication; starting a heartbeat mechanism according to the opening event in the standardized events, identifying a heartbeat response and recording the latest heartbeat time, and triggering reconnection when disconnection or timeout occurs; performing exponential backoff reconnection scheduling according to the disconnection signal; and publishing the connection state and messages to the business layer through a subscription interface according to the standardized events and the reconnection stop signal. The application can maintain the consistency and stability of connection behavior under the difference of multiple terminals.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of network communication technology, and more specifically relates to a cross-terminal WebSocket long connection management method, system, device and medium. Background Technology

[0002] In cross-platform application scenarios, different runtime environments such as H5, WeChat Mini Programs, and mobile App-Plus coexist. To enable the server to proactively push notification messages to each platform, WebSocket long-lived connections, with their full-duplex communication capabilities, have become a critical infrastructure. However, different runtime environments exhibit significant differences in their support for the underlying capabilities of WebSocket and the form of application programming interfaces (APIs): some runtime environments have unstable or limited support for authentication information carried in HTTP headers; the type of connection object and the event callback interface also differ; some runtime environments return a direct connection instance, while others return a task object or a commitment object; and the return order of the start event and the connection task object varies from platform to platform. These differences make it difficult to directly reuse the same set of connection management and event binding logic across platforms, requiring developers to write a large number of conditional statements to adapt to different runtime environments.

[0003] Even with adaptations to handle connection establishment logic separately for each end, existing technologies still lack a unified mechanism for dealing with the uncertainty of the return order of the start event and the connection task object. During connection establishment, the return order of the start event and the connection task object varies from end to end and is unpredictable: if the start event arrives before the connection task object, initialization cannot be completed if the connection task object has not yet been obtained; if the connection task object returns before the start event arrives, immediate initialization may cause logic failure because the connection has not yet been truly established. Without a coordination mechanism, existing practices easily lead to the repeated execution of the same connection initialization logic, such as the heartbeat timer being started multiple times or being missed, such as the first packet processing not being triggered, directly affecting the normal operation of the connection.

[0004] The recovery mechanism after a connection is lost also faces challenges. In existing technologies, each business module or page typically implements its own reconnection logic. Due to the lack of a unified standard for disconnection detection and a reconnection scheduling mechanism, multiple modules may initiate reconnection requests simultaneously when the network fluctuates frequently, resulting in a large number of requests being sent to the server, creating a reconnection storm. Furthermore, when the network is offline for a long time, the lack of continuous reconnection recovery capabilities means that the connection cannot be rebuilt in a timely manner after the network recovers. In addition, the reception of connection status and notification messages is scattered across various business layers. The business layers cannot perceive the connection status and receive messages in a unified way, creating strong coupling with the underlying connection logic and further increasing the maintenance difficulty. Summary of the Invention

[0005] To address the above issues, the present invention aims to provide a cross-platform WebSocket long connection management method, system, device, and medium. By uniformly managing the differences in connection establishment across multiple platforms, coordinating race conditions during connection establishment, ensuring the reliability of event arrival, and controlling disconnection and reconnection behavior, the consistency and stability of WebSocket long connection behavior in a multi-platform environment are comprehensively achieved.

[0006] To achieve the above objectives, the present invention employs the following technical solution: In a first aspect, embodiments of this application provide a cross-platform WebSocket long connection management method, comprising the following steps: S1: Configure the WebSocket connection parameters for different ends in a unified manner, generate a standardized configuration object, and construct a connection Uniform Resource Locator based on the standardized configuration object; S2: Initiate a connection based on the standardized configuration object and the connection Uniform Resource Locator, generate a current connection identifier, and process the return order of the start event and the connection task object through state variables to obtain the connection task object and the current connection identifier; S3: Based on the connection task object and the current connection identifier, register the event using the local event binding method, and use the global event interface as a backup binding channel to deduplicate the received events to obtain standardized events; S4: Start the heartbeat mechanism according to the start event in the standardized event. In the heartbeat mechanism, heartbeat request messages are sent at fixed heartbeat intervals. The heartbeat response returned by the server is identified and the most recent heartbeat time is recorded. A disconnection trigger signal is obtained when a disconnection or heartbeat timeout occurs. S5: Perform reconnection scheduling according to the disconnection trigger signal: In the case of non-active shutdown, calculate the reconnection waiting time according to the exponential backoff strategy. When the number of reconnection attempts has not reached the maximum number of reconnection attempts, re-execute step S2 according to the reconnection waiting time. When the number of reconnection attempts reaches the maximum number of reconnection attempts, stop automatic scheduling and obtain a reconnection stop signal. S6: Based on the standardized event and the reconnection stop signal, publish connection status and message data to the business layer through the unified subscription interface.

[0007] In an optional implementation, step S1 includes: The system obtains three types of configuration sources: basic configuration objects, general overlay configuration objects, and client-specific overlay configuration objects. The basic configuration object contains protocol fields, host fields, path fields, connection timeout fields, and close code fields. The general overlay configuration object contains protocol overlay fields, host overlay fields, path overlay fields, connection timeout fields, and close code overlay fields. The client-specific overlay configuration objects correspond to H5 client, WeChat mini-program client, and mobile App-Plus client, respectively. Each client-specific overlay configuration object contains protocol fields, host fields, path fields, connection timeout fields, close code fields, and global fallback enable fields. Using the basic configuration object, the general coverage configuration object, and the terminal-specific coverage configuration object as input, and following the priority order of terminal-specific coverage configuration object > general coverage configuration object > basic configuration object, the protocol field, host field, path field, connection timeout field, and close code field are merged at the field level: For each field, a non-empty value of the field in the terminal-specific coverage configuration object is taken; if the field in the terminal-specific coverage configuration object is empty or does not exist, a non-empty value of the field in the general coverage configuration object is taken; if the field in the general coverage configuration object is empty or does not exist, the non-empty value of the field in the general coverage configuration object is taken. If the value is not null, then the non-null value of the field in the basic configuration object is taken, and the result is used as the value of the corresponding field in the standardized configuration object to generate a standardized configuration object. Specifically, if the host field of the H5 side is null, then the host address of the current page is obtained as the value of the host field in the standardized configuration object. If the protocol field is not explicitly overridden, then wss or ws is taken as the value of the protocol field in the standardized configuration object according to whether the current page protocol type is HTTPS or HTTP. If the path field is null, then the default path is taken as the value of the path field in the standardized configuration object, and the default path is / web-link / publish. Obtain the Authorization and clientid parameters from the authentication information passed in from the business layer. Perform URL encoding on the Authorization and clientid parameters respectively and then concatenate them into the query parameter field. Concatenate the protocol field, host field, path field and query parameter field in the standardized configuration object in sequence to generate a connection Uniform Resource Locator.

[0008] In an optional implementation, step S2 includes: Based on the standardized configuration object and the connection Uniform Resource Locator, a connection timeout threshold is set, and a connection request is initiated, wherein the connection timeout threshold is set according to the connection timeout field in the standardized configuration object; The following state variable initialization process is executed: Initialize the current connection identifier to the identifier value of this connection, initialize the connection identifier with processed open events to null, initialize the open wait flag to false, initialize the manual close flag to false, initialize the socket task object to null, initialize the socket commitment object to null, initialize the reconnection attempt count to 0, initialize the reconnection timer to null, initialize the connection identifier with processed close events to null, and initialize the subscriber to null. The current connection identifier is incremented and used as the current connection identifier for this connection. Listen for the return of the start event and the connection task object; if the start event returns before the connection task object, assign the connection identifier of the processed start event to the current connection identifier, and set the start waiting flag to true when the socket task object is not ready, waiting for the socket task object to return; if the connection task object returns before the start event, temporarily store the connection task object in the socket task object, waiting for the start event to be triggered. After the connection task object returns, the following judgment is performed based on the connection task object, the start-up waiting flag, the connection identifier of the processed start-up event, and the current connection identifier: If the start-up waiting flag is true, the connection identifier of the processed start-up event is equal to the current connection identifier, and the connection task object is not empty, then the pending start-up initialization logic is executed, the heartbeat mechanism is started, and the current connection identifier and the connection task object are obtained; if the start-up event is received repeatedly when the connection identifier of the processed start-up event is equal to the current connection identifier, then the repeated start-up event is ignored.

[0009] In an optional implementation, step S3 includes: Detect the current endpoint environment type based on the connection task object and the current connection identifier; Select the corresponding local event binding method according to the terminal environment type, and register start event, message event, error event and close event for the connection task object; According to the global fallback enable field in the standardized configuration object, when the global fallback enable field indicates that there is a risk of local event binding being unreachable, a global event interface is registered as a backup binding channel, and the same current connection identifier is registered only once for the global event interface; For start events, message events, error events, and close events arriving via local event binding or global event interface, deduplication is performed: For start events, the current connection identifier is compared with the connection identifier of a previously processed start event; if they match, the start event is discarded; otherwise, a deduplicated start event is obtained. For close events, the current connection identifier is compared with the connection identifier of a previously processed close event; if they match, the close event is discarded; otherwise, the connection identifier of the previously processed close event is assigned to the current connection identifier, and a deduplicated close event is obtained. For error events, the current connection identifier is compared with the connection identifier of a processed closure event. If they match, the error event is discarded; otherwise, the connection identifier of the processed closure event is assigned to the current connection identifier, resulting in a deduplicated error event. For message events, the message identifier or notification identifier is extracted as a key. The recent message identifier set is queried. If the key already exists in the recent message identifier set, the message event is discarded; otherwise, the key is added to the recent message identifier set, resulting in a deduplicated message event. The deduplicated open event, deduplicated message event, deduplicated error event, and deduplicated close event are treated as standardized events.

[0010] In an optional implementation, step S4 includes: According to the enable event in the standardized event, the heartbeat mechanism is started, specifically including: when the enable event in the standardized event arrives, a heartbeat timer is started according to the fixed heartbeat interval, and a heartbeat request message is periodically sent through the connection at the fixed heartbeat interval, wherein the heartbeat request message is the string "ping"; Obtain the raw response data returned by the connection, and perform compatibility recognition on the heartbeat response returned by the server: check if the raw response data is the string "pong", if so, it is recognized as a heartbeat response; if the raw response data is a JSON format message, extract the values ​​of the cmd field, type field, event field and raw field in the JSON format message in sequence, and match the value of each field with the string "pong" or "ping". If the value of any field matches the string "pong" or "ping", it is recognized as a heartbeat response; If the response is identified as a heartbeat, the current system time is obtained and the most recent heartbeat time is written. The heartbeat identifier is extracted and recorded. If the response is not identified as a heartbeat, the original response data is treated as a business message. Based on the most recent heartbeat time and the current system time, calculate the difference between the current system time and the most recent heartbeat time. If the difference is greater than the heartbeat timeout threshold, actively close the current connection and keep the manual close flag false to obtain a disconnection trigger signal.

[0011] In an optional implementation, step S5 includes: Obtain the manual shutdown flag, obtain the current reconnection attempt count, and determine the maximum reconnection delay and maximum reconnection attempt count from the standardized configuration object; If the manual shutdown flag is true, then reconnection scheduling is prohibited and the process is terminated; If the manual close flag is false, the scheduling queue is represented by a unique reconnection timer. The status of the reconnection timer is queried: if the reconnection timer is not empty, new reconnection tasks are rejected from being enqueued and the process is terminated; if the reconnection timer is empty, the current reconnection attempt count is incremented according to... Calculate the reconnection waiting time, where Indicates the first Reconnection wait time after the first failure This is the current reconnection attempt count after incrementing. The reconnection waiting time is set as a delay parameter for the reconnection timer. After the reconnection timer is triggered, the reconnection timer is cleared first. The current number of reconnection attempts after clearing is obtained, and the maximum number of reconnection attempts is obtained. If the current reconnection attempt count after clearing does not reach the maximum reconnection attempt count, then based on the standardized configuration object and the connection unified resource locator, jump to step S2 to re-initiate the connection; if the current reconnection attempt count after clearing reaches the maximum reconnection attempt count, then stop automatic scheduling and obtain a reconnection stop signal; Once the connection is successfully established and enters the open state, the number of reconnection attempts is reset to zero. Once the service actively closes the connection or the authentication information changes, the number of reconnection attempts is reset to zero. When the manual close flag is true, the reconnection timer is canceled and the jump to step S2 is prohibited.

[0012] In an optional implementation, step S6 includes: A subscription-based distribution model is provided at the business access layer, and notification message subscription and connection status subscription are made available to the business layer through a unified subscription interface; When the business layer calls the unified subscription interface, it obtains the subscription callback passed by the business layer and stores it in the subscriber. The subscriber stores the subscription callback with the subscription callback identifier as the key. The subscription callback includes at least the notification message subscription callback and the connection status subscription callback. When the open event in the standardized event is obtained, the connection is published to the business layer through the connection state subscription callback; when the close event in the standardized event is obtained, the connection is published to the business layer through the connection state subscription callback; when the error event in the standardized event is obtained, the connection error is published to the business layer through the connection state subscription callback. When the business message is obtained, the business message is published to the business layer through the notification message subscription callback; When the reconnection stop signal is received, the reconnection status data that has been exhausted is published to the business layer through the connection status subscription callback; When a page or component unload signal is received, the unsubscribe flag passed from the business layer is obtained, the corresponding subscription callback is removed from the subscriber, and the subscription callback is terminated from receiving any subsequent events and messages.

[0013] Secondly, embodiments of this application also provide a cross-platform WebSocket long connection management system, including: The configuration generation module is used to uniformly configure the WebSocket connection parameters of different ends, generate a standardized configuration object, and construct a connection Uniform Resource Locator based on the standardized configuration object; The connection establishment module is used to initiate a connection based on the standardized configuration object and the connection Uniform Resource Locator, generate a current connection identifier, and process the return order of the start event and the connection task object through state variables to obtain the connection task object and the current connection identifier. The event binding module is used to register events using a local event binding method based on the connection task object and the current connection identifier, and to use the global event interface as a backup binding channel to deduplicate the received events to obtain standardized events. The heartbeat management module is used to start the heartbeat mechanism according to the start event in the standardized event. In the heartbeat mechanism, heartbeat request messages are sent at fixed heartbeat intervals, the heartbeat response returned by the server is identified and the most recent heartbeat time is recorded, and a disconnection trigger signal is obtained when a disconnection or heartbeat timeout occurs. The reconnection scheduling module is used to perform reconnection scheduling according to the disconnection trigger signal: in the case of non-active shutdown, the reconnection waiting time is calculated according to the exponential backoff strategy; when the number of reconnection attempts has not reached the maximum number of reconnection attempts, the connection establishment module is triggered to re-initiate the connection according to the reconnection waiting time; when the number of reconnection attempts reaches the maximum number of reconnection attempts, automatic scheduling is stopped and a reconnection stop signal is obtained. The subscription and distribution module is used to publish connection status and message data to the business layer through a unified subscription interface based on the standardized events and the reconnection stop signal.

[0014] Thirdly, embodiments of this application also provide an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the steps of the cross-end WebSocket long connection management method as described in any of the above.

[0015] Fourthly, embodiments of this application also provide a storage medium storing a computer program thereon, which, when executed by a processor, implements the steps of the cross-end WebSocket long connection management method as described in any of the above.

[0016] As can be seen from the above technical solutions, the present invention has the following advantages: The cross-platform WebSocket long connection management method provided in this application unifies the entire process of WebSocket long connection from configuration, connection establishment, event binding, heartbeat keep-alive to reconnection scheduling and subscription distribution. This ensures the consistency and stability of connection behavior under the differences of different running terminals, significantly reducing the complexity and maintenance cost of multi-terminal access. At the same time, through state machine coordination, dual-channel event binding and multi-level deduplication, heartbeat keep-alive and exponential backoff reconnection mechanisms, the reliability, activity and convenience of business access of long connection are effectively guaranteed, providing a unified, efficient and scalable basic technical solution for multi-terminal real-time notification push scenarios.

[0017] This application achieves unified management and flexible adaptation of WebSocket connection parameters across different platforms by unifying and abstracting the parameters for different platforms. It employs a three-tier configuration system: basic configuration, general overriding, and platform-specific overriding. Fields are merged according to a priority order: platform-specific overriding takes precedence over general overriding, and general overriding takes precedence over basic configuration. Furthermore, addressing the issue of unstable authentication header support on some platforms, authentication information is uniformly transmitted as URL query parameters, ensuring consistency in authentication methods and connection behavior across the three platforms. This allows the same configuration and connection logic to function correctly on H5, WeChat Mini Programs, and App-Plus platforms, greatly simplifying the multi-platform access process and reducing access instability caused by platform differences.

[0018] This application introduces a connection state machine mechanism. By generating a unique connection identifier and combining it with state variables such as the connection identifier of the processed start event, the start wait flag, and the manual close flag, the mechanism coordinates the return order of the start event and the connection task object, ensuring that the initialization logic of the same connection is triggered only once. Regardless of whether the start event or the connection task object occurs first, the initialization logic can be executed correctly or delayed by judging the state variables. This effectively avoids duplicate initialization, missed initialization, or race conditions caused by uncertain return order, significantly improving the reliability and robustness of the connection establishment process.

[0019] This application employs a dual-channel event binding strategy, primarily using local event binding and secondarily using a global event interface. When the local event binding of the connection object returned by the client is unreachable, the global event interface serves as a fallback, ensuring that start, message, error, and close events are reliably delivered across all clients. Simultaneously, a multi-level deduplication mechanism for start, close, error, and message events avoids duplicate callbacks across both channels. Building upon this, a subscription-based distribution model is provided at the business access layer. Notification messages and connection state changes are published to the business layer via a unified subscription interface. The business layer only needs to receive messages and perceive the state through subscription callbacks, eliminating the need for scattered client-side judgment and event binding code across various pages or modules. This decouples the business layer from the underlying connection logic, significantly improving code maintainability and scalability.

[0020] This application employs a fixed heartbeat interval to periodically send heartbeat request messages and performs multi-format compatibility recognition on the heartbeat responses returned by the server. It can determine the response type based on the conventions of multiple fields in the raw string or JSON message, enabling the method to adapt to different backend implementations. Simultaneously, by recording the most recent heartbeat time and using this to detect the connection health status, it proactively closes the connection and triggers a reconnection process when the heartbeat times out, effectively preventing abnormal situations such as connection freezes and zombie connections, ensuring the continuous activity of long-lived connections.

[0021] This application employs an exponential backoff strategy to control reconnection waiting time, reducing reconnection requests as the number of failures increases. It also sets a maximum reconnection delay limit and a maximum number of reconnection attempts, effectively avoiding a "reconnection storm" caused by a large number of concentrated reconnection requests during network jitter, and preventing endless reconnection attempts when the network is offline for extended periods. A unique reconnection timer controls the reconnection queue, ensuring that only a single reconnection task is scheduled at any given time. Furthermore, a manual close flag is set to block automatic reconnection when a user or service actively closes the connection, preventing accidental reconnections. Through these mechanisms, this application significantly reduces the impact on the server while ensuring connection recovery capabilities and achieving controllability in the reconnection process. Attached Figure Description

[0022] To more clearly illustrate the technical solution of the present invention, the accompanying drawings used in the description will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0023] Figure 1 A flowchart illustrating the cross-platform WebSocket long connection management method provided in this application.

[0024] Figure 2 A schematic diagram of the cross-platform WebSocket long connection management system provided in this application.

[0025] Figure 3 A schematic diagram of the structure of the electronic device provided in this application. Detailed Implementation

[0026] The various embodiments of this disclosure will be described more fully in the detailed steps of the cross-platform WebSocket long connection management method described below. This disclosure may have various embodiments, and adjustments and changes may be made therein. However, it should be understood that there is no intention to limit the various embodiments of this disclosure to the specific embodiments disclosed herein, but rather this disclosure should be understood to cover all adjustments, equivalents, and / or alternatives falling within the spirit and scope of the various embodiments of this disclosure.

[0027] In the following, the terms “comprising” or “may include”, which may be used in various embodiments of this disclosure, indicate the presence of the disclosed functions, operations, or elements, and do not limit the addition of one or more functions, operations, or elements. Furthermore, as used in various embodiments of this disclosure, the terms “comprising,” “having,” and their cognates are intended only to indicate a particular feature, number, step, operation, element, component, or combination of the foregoing, and should not be construed as primarily excluding the presence of one or more other features, numbers, steps, operations, elements, components, or combinations of the foregoing, or the possibility of adding one or more combinations of the foregoing.

[0028] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0029] Please see Figure 1The diagram shows a flowchart of a cross-platform WebSocket long connection management method in a specific embodiment. The method includes the following steps: S1: Configure the WebSocket connection parameters for different ends in a unified manner, generate a standardized configuration object, and construct a connection Uniform Resource Locator based on the standardized configuration object.

[0030] In a specific implementation, three types of configuration sources are first obtained as input: a basic configuration object, a general overriding configuration object, and a client-specific overriding configuration object. The basic configuration object is the system's preset default configuration, containing protocol fields, host fields, path fields, connection timeout fields, and close code fields, serving as a fallback configuration for all clients. The general overriding configuration object is an optional configuration, containing optional fields with the same names as the client-specific overriding configuration object, including at least protocol overriding fields, host overriding fields, path overriding fields, connection timeout overriding fields, and close code overriding fields, used for uniformly adjusting general parameters under specific business scenarios. The client-specific overriding configuration objects correspond to H5 clients, WeChat mini-program clients, and mobile App-Plus clients, respectively. Each client environment has an independent client-specific configuration object, containing protocol fields, host fields, path fields, connection timeout fields, close code fields, and a global fallback enable field, used for fine-tuning configuration based on the characteristics of different running clients.

[0031] After obtaining the three types of configuration sources, the basic configuration object, general overlay configuration object, and client-specific overlay configuration object are used as input. Following the priority order of client-specific overlay configuration object > general overlay configuration object > basic configuration object, the protocol field, host field, path field, connection timeout field, and close code field are merged at the field level. The specific merging rules are as follows: for each field, first, a non-empty value from the client-specific overlay configuration object is taken as the priority value; if the field is empty or does not exist in the client-specific overlay configuration object, then a non-empty value from the general overlay configuration object is taken; if the field is empty or does not exist in the general overlay configuration object, then a non-empty value from the basic configuration object is taken. The resulting value is used as the value of the corresponding field in the standardized configuration object, ultimately generating a complete standardized configuration object. This field-by-field merging method ensures both the flexibility of client-specific configuration and guarantees that unconfigured fields can be covered by general or basic configuration.

[0032] During the generation of the standardized configuration object, special handling is required for the H5 page. If the host field on the H5 page is empty, the host address of the current page is used as the value of the host field in the standardized configuration object, i.e., it is used directly. Using the host address ensures the connection target is from the same origin as the current page, avoiding cross-origin issues. If the protocol field is not explicitly overridden, it adaptively selects a value based on the current page's protocol type: `wss` is used if the current page's protocol is HTTPS, and `ws` is used if the current page's protocol is HTTP, ensuring protocol matching and compatibility. If the path field is empty, the default path is used as the value for the path field in the standardized configuration object; this default path is ` / web-link / publish`.

[0033] After the standardized configuration object is generated, the authentication information passed from the business layer is obtained, and the Authorization and clientid parameters are extracted from it. Since the authentication information may contain special characters (such as spaces, forward slashes, plus signs, etc.), the Authorization and clientid parameters need to be URL-encoded separately to avoid URL parsing errors. The encoded Authorization and clientid parameters are then concatenated into the query parameter field according to the URL query parameter format, specifically: Finally, the protocol field, host field, path field, and query parameter field in the standardized configuration object are concatenated in sequence to generate a complete Uniform Resource Locator (URL). For example, the format of the URL after concatenation is: wss: / / gateway.example.com / web-link / publish?Authorization=Bearer%20xxxxx&clientid=user123.

[0034] S2: Initiate a connection based on the standardized configuration object and the connection Uniform Resource Locator, generate a current connection identifier, and process the return order of the start event and the connection task object through state variables to obtain the connection task object and the current connection identifier.

[0035] In a specific implementation, a connection timeout threshold is first set based on the connection timeout field in the standardized configuration object. For example, the connection timeout threshold is set to 10,000 milliseconds. If the connection fails to be established within this time, a connection timeout is determined. Then, a connection request is initiated based on the connection's Uniform Resource Locator (URL). Different endpoints use different underlying connection creation methods: in the H5 endpoint, through... Establish a connection; in the WeChat Mini Program or App-Plus, initiate a connection via the corresponding SocketTask API. Regardless of the underlying implementation used, ensure that the timeout control for connection requests is consistently effective.

[0036] While initiating a connection, the initialization process for state variables is executed. Specifically, the current connection identifier is initialized to the identifier value of this connection, which uniquely identifies a connection session and can be a globally incrementing integer or a UUID. The connection identifier with processed open events is initialized to null; this variable records the connection identifiers that have completed the open initialization logic to prevent duplicate processing. The open wait flag is initialized to false; this flag marks whether an open event has arrived but has not yet been processed. The manual close flag is initialized to false; this flag distinguishes between active business closure and passive disconnection due to network anomalies. The socket task object is initialized to null; this object stores the task object returned by the underlying connection. The socket promise object is initialized to null; this object handles the Promise returned by asynchronous connections. The reconnection attempt count is initialized to 0; this records the number of reconnection attempts after the current connection fails. The reconnection timer is initialized to null; this stores the timer handle for reconnection scheduling. The connection identifier with processed close events is initialized to null; this records the connection identifiers that have completed the close processing to prevent duplicate closures. The subscriber is initialized to null; this stores the subscription callbacks from the business layer. The aforementioned state variables are shared states throughout the entire process from steps S2 to S5. They are reset uniformly each time a new connection is established, ensuring the consistency and predictability of the connection state.

[0037] After the state variables are initialized, the current connection identifier is incremented and used as the current connection identifier for this connection, ensuring that the identifier of each new connection is unique. Then, the system listens for the start event and the return of the connection task object, executing different coordination logic based on the order in which they arrive.

[0038] In the first scenario, if the start event returns before the connection task object, the connection identifier of the processed start event is assigned the current connection identifier, indicating that the start event has been triggered. If the socket task object is not yet ready, the start wait flag is set to true, indicating that there is pending start initialization logic, and then the system waits for the socket task object to return. In this case, the start initialization logic is not executed immediately but is delayed until after the socket task object returns, ensuring that the connection is truly available when the initialization logic is executed.

[0039] In the second scenario, if the connection task object returns before the open event, the connection task object is temporarily stored in the socket task object, waiting for the open event to trigger before executing the initialization logic. In this case, since the open event has not yet arrived, the initialization logic is not executed, avoiding incorrectly starting the heartbeat or sending the first packet before the connection is actually established.

[0040] After the connection task object returns, retrieve the connection task object, the start-wait flag, the connection identifier of the processed start-up event, and the current connection identifier, and perform a comprehensive judgment. If the start-wait flag is true, the connection identifier of the processed start-up event equals the current connection identifier, and the connection task object is not empty, then execute the pending start-up initialization logic, start the heartbeat mechanism, and obtain the current connection identifier and the connection task object, indicating that the establishment and initialization process of this connection has been completed. If a duplicate start-up event is received when the connection identifier of the processed start-up event equals the current connection identifier, then ignore the duplicate start-up event.

[0041] Through the above coordination mechanism, regardless of the return order of the start event and the connection task object, the initialization logic is executed correctly and only once.

[0042] S3: Based on the connection task object and the current connection identifier, register the event using the local event binding method, and use the global event interface as a backup binding channel to obtain the standardized event after deduplication of the received event.

[0043] In a specific implementation, the current endpoint environment type is first detected based on the connection task object and the current connection identifier. This endpoint environment type detection can be achieved through runtime environment checks: in the H5 endpoint, it checks for the existence of a WebSocket global object and the absence of a WeChat Mini Program-specific global object; in the WeChat Mini Program endpoint, it checks for the existence of a wx or uni object and the availability of Mini Program-specific APIs; in the App-Plus endpoint, it checks for the existence of a plus or uni object and the availability of App-Plus-specific APIs. After detecting the endpoint environment type, the corresponding local event binding method is selected based on the endpoint environment type, registering start events, message events, error events, and close events for the connection task object.

[0044] For the H5 client, since it directly returns a WebSocket instance, event listeners are registered using the `addEventListener` method. Example code is as follows:

[0045]

[0046]

[0047]

[0048] In H5, addEventListener is the standard event registration method, which supports multiple listeners to exist at the same time and has high stability.

[0049] For WeChat Mini Programs, since the SocketTask object in the Mini Program provides dedicated on methods, the SocketTask class is used. , , , The method performs event binding. Example code is as follows: , , , In the mini-program, the `on` series of methods is the officially recommended binding method.

[0050] For the App-Plus platform, since the uni-app framework may return a SocketTask object or a Promise object, it's necessary to first determine the type of the returned object before calling the corresponding on method. If a SocketTask object is returned, the usage is similar to that in WeChat Mini Programs. , , , The method, if returning a Promise object, requires waiting for the Promise to resolve before binding. By providing a unified encapsulation in the App-Plus platform, different return types can be handled correctly.

[0051] After local event binding is complete, the global fallback enable field in the standardized configuration object is used to determine whether the global event interface needs to be enabled as a backup binding channel. When the global fallback enable field indicates a risk of local event binding being unreachable, the global event interface is registered as a backup binding channel. Specifically, the global event interface for H5 is a custom event on the window global object, while the global event interface for WeChat Mini Programs and App-Plus is... , , and The global event interface is registered only once for the same current connection identifier to avoid duplicate event triggering caused by repeated registration.

[0052] When an event arrives via a local event binding, it triggers normally and enters the deduplication process. When an event arrives via the global event interface, it also enters the deduplication process. The specific deduplication process is as follows: For each open event, the current connection identifier is compared with the connection identifier of a previously processed open event. If they match, it indicates that the connection corresponding to the open event has already been initialized, and the event is a duplicate, so it is discarded. If they do not match, it indicates that the connection corresponding to the open event has not yet been initialized, and the deduplicated open event is obtained.

[0053] For a close event, the current connection identifier is compared with the connection identifier of a previously processed close event. If they match, it indicates that the connection corresponding to the close event has already undergone close logic processing, and the event is a duplicate; therefore, the close event is discarded. If they do not match, the connection identifier of the previously processed close event is assigned to the current connection identifier, indicating that the close logic for the current connection has been processed, and a deduplicated close event is obtained. This mechanism ensures that the close logic for the same connection is executed only once, avoiding duplicate resource releases or duplicate notifications to the business layer.

[0054] For error events, the same deduplication logic as for closure events is used, comparing the current connection identifier with the connection identifier of a previously processed closure event. If they match, the error event is discarded; otherwise, the connection identifier of the previously processed closure event is assigned to the current connection identifier, resulting in the deduplicated error event. Error events and closure events share the same deduplication identifier because in real-world network environments, a connection failure often triggers both an error event and a closure event simultaneously; sharing the identifier effectively prevents the same failure from being processed twice.

[0055] For a message event, the message identifier or notification identifier is extracted as a key, and the recent message identifier set is queried. This recent message identifier set is a fixed-capacity set, for example, with a capacity of 100, used to cache recently received message identifiers. If the key already exists in the recent message identifier set, it indicates that the message has arrived repeatedly, and the message event is discarded. If the key does not exist in the recent message identifier set, the key is added to the set, and the deduplicated message event is obtained. This deduplication mechanism effectively prevents duplicate message distribution caused by dual-channel event binding.

[0056] The deduplicated start events, deduplicated message events, deduplicated error events, and deduplicated close events are standardized events. Through the above event binding and deduplication mechanism, it is ensured that the four types of events can reliably reach each platform and are not repeatedly distributed, effectively solving the problem of differences in cross-platform event callback mechanisms.

[0057] S4: Start the heartbeat mechanism according to the start event in the standardized event. In the heartbeat mechanism, heartbeat request messages are sent at fixed heartbeat intervals. The heartbeat response returned by the server is identified and the most recent heartbeat time is recorded. A disconnection trigger signal is obtained when a disconnection occurs or the heartbeat times out.

[0058] In a specific implementation, when the "Start" event in the standardized events arrives, it indicates that the WebSocket connection has been successfully established, and the heartbeat mechanism is initiated. A heartbeat timer is started according to the fixed heartbeat interval specified in the standardized configuration object. This fixed heartbeat interval is set to 30,000 milliseconds by default, meaning a heartbeat request message is sent every 30 seconds. The heartbeat request message is the string "ping" and is sent directly to the server through the connection. The heartbeat request message has a concise format, facilitating quick parsing and response by the server, while reducing unnecessary network overhead.

[0059] After the heartbeat timer starts, heartbeat request messages are periodically sent through the connection at fixed heartbeat intervals. The time of each heartbeat transmission is recorded for subsequent heartbeat timeout determination. In some embodiments, the heartbeat request message may also carry a heartbeat identifier, which is used to associate with the heartbeat response returned by the server to facilitate troubleshooting network latency issues.

[0060] While sending heartbeat request messages, the system continuously monitors the raw response data returned by the connection and performs compatibility identification on the heartbeat responses returned by the server. Since different backend services implement heartbeat responses differently, this implementation adopts a multi-format compatibility identification strategy. The specific identification process is as follows: First, check if the original response data is the string "pong". If it is, it is directly identified as a heartbeat response. This is the simplest and most commonly used heartbeat response format, suitable for most backend implementations.

[0061] If the original response data is not the string "pong", then check if it is a JSON format message. If it is a JSON format message, then extract the fields in the JSON message that may carry the heartbeat identifier. Specifically, extract the following fields in sequence: Fields Fields fields and The field values ​​are matched against the string "pong" or "ping". If any field value matches the string "pong" or "ping", it is identified as a heartbeat response.

[0062] For example, the server might return a heartbeat response in JSON format, such as... Then check The field value "pong" matches "pong", indicating a heartbeat response. For example, the server returns... Then check The field value "PONG" matches "pong" regardless of case, and is identified as a heartbeat response. For example, the server returns... Then check The field value "pong" matches "pong" and is identified as a heartbeat response. Through the above-described multi-field, multi-format compatible recognition strategy, this implementation can adapt to different backend implementations without the need to customize heartbeat logic for each backend separately.

[0063] If a heartbeat response is identified, the current system time is obtained and the most recent heartbeat time is written. Simultaneously, the heartbeat identifier is extracted and recorded for subsequent heartbeat timeout detection. Heartbeat responses are not included in the business message distribution process; that is, they are not published to the business layer through the subscription interface to avoid the business layer receiving meaningless heartbeat data.

[0064] If the response is not identified as a heartbeat, the raw response data will be used as a business message for subsequent publishing to the business layer. Business messages can be any application-layer data, such as to-do reminders, system notifications, or data updates, and can be in JSON format. .

[0065] During the heartbeat mechanism's operation, connection health checks are continuously performed based on the most recent heartbeat time and the current system time. Specifically, the difference between the current system time and the most recent heartbeat time is calculated. If this difference exceeds the heartbeat timeout threshold, the connection is considered inactive, meaning the server did not respond to the heartbeat request within the timeout period. The default heartbeat timeout threshold is set to 60,000 milliseconds, twice the interval between two heartbeats (30,000 milliseconds), providing the server with sufficient response time. When a heartbeat timeout is detected, the current connection is proactively closed, and the manual close flag is kept false to distinguish it from scenarios where the business actively closes the connection. Subsequently, a disconnection trigger signal is received to trigger reconnection scheduling. Through the above heartbeat keep-alive and timeout detection mechanism, abnormal situations such as connection freezes and zombie connections are effectively prevented, ensuring the continuous activity of long-lived connections.

[0066] S5: Perform reconnection scheduling based on the disconnection trigger signal: In the case of non-active shutdown, calculate the reconnection waiting time according to the exponential backoff strategy. When the number of reconnection attempts has not reached the maximum number of reconnection attempts, re-execute step S2 according to the reconnection waiting time. When the number of reconnection attempts reaches the maximum number of reconnection attempts, stop automatic scheduling and obtain a reconnection stop signal.

[0067] In a specific implementation, after a disconnection trigger signal is obtained, the manual shutdown flag and the current number of reconnection attempts are first obtained, and a reconnection scheduling decision is executed based on the maximum reconnection delay and the maximum number of reconnection attempts in the standardized configuration object.

[0068] The first step in the decision-making process is to check the manual disconnection flag. If the manual disconnection flag is true, it indicates that the current connection loss was actively triggered by the service (e.g., user logout or service module uninstallation), rather than a passive disconnection caused by network anomalies. In this case, reconnection scheduling is prohibited and the process is terminated to avoid erroneous reconnections when the service actively disconnects.

[0069] If the manual close flag is false, it indicates that the current connection loss was caused by passive reasons such as network anomalies, server-side anomalies, or heartbeat timeouts, requiring reconnection scheduling. In this case, a unique reconnection timer represents the scheduling queue. First, the reconnection timer status is checked. If the reconnection timer is not empty, it indicates that there is already a pending reconnection task. At this point, new reconnection tasks are rejected from the queue, and the process terminates, ensuring that only one reconnection task is scheduled at any given time. This avoids a reconnection storm caused by multiple modules or multiple disconnection events triggering reconnections simultaneously.

[0070] If the reconnection timer is empty, then execute the reconnection scheduler. Record the current number of reconnection attempts. Incrementing, the reconnection waiting time is calculated according to the exponential backoff formula. Specifically:

[0071] in Indicates the first Reconnection wait time after the first failure This is the maximum reconnection delay, with a default value of 30,000 milliseconds. This is the incremented current reconnection attempt count. Start from 1.

[0072] According to the above formula, the first reconnection is... The waiting time is Milliseconds, meaning the first reconnection will be executed 2 seconds after the initial disconnection. The second reconnection will then... The waiting time is Milliseconds. The third time was 8000 milliseconds, the fourth time was 16000 milliseconds, and the fifth time and thereafter were... Milliseconds represent the maximum reconnection latency, after which the waiting time stops increasing. This exponential backoff strategy causes the reconnection frequency to gradually decrease with the number of failures, avoiding a large number of reconnection requests being sent at once during periods of frequent network jitter, while ensuring that the connection can be re-established promptly after the network recovers.

[0073] After the reconnection wait time is calculated, it is used as a delay parameter to set the reconnection timer. When the reconnection timer is triggered, it is first cleared and its handle released. Then, the current reconnection attempt count and the maximum reconnection attempt count are obtained. If the current reconnection attempt count after clearing does not reach the maximum reconnection attempt count (default value is 8), the process jumps to step S2 to re-initiate the connection based on the standardized configuration object and the connection's Uniform Resource Locator, starting a new round of connection establishment. If the current reconnection attempt count after clearing reaches the maximum reconnection attempt count (default value is 8), automatic scheduling stops, and a reconnection stop signal is received to notify the business layer that reconnection has been exhausted, waiting for the business side to explicitly call the connection interface to re-initiate the connection. This mechanism avoids endless reconnection attempts when the network is offline for extended periods, saving device power and network resources.

[0074] During the reconnection scheduling process, the reconnection attempt counter needs to be reset in the following situations: when the connection successfully enters the open state, it indicates a successful reconnection, and the reconnection attempt count is reset to zero to prepare for possible subsequent disconnections; when the service actively closes the connection, it indicates that the disconnection is a controllable behavior of the service, and the reconnection attempt count is reset to zero; when the authentication information changes (e.g., user token refresh or re-login), it indicates that the connection needs to be re-established, and the reconnection attempt count is reset to zero. When the manual close flag is true, the reconnection timer is canceled and the jump to step S2 is prohibited to ensure that no automatic reconnection is triggered after the service actively closes the connection.

[0075] In this implementation, the maximum number of reconnection attempts is set to 8. When the number of reconnection attempts reaches this limit, automatic reconnection scheduling is stopped, and the status data of reconnection exhaustion is published to the business layer through the subscription interface. At the same time, it waits for the business side to explicitly call the connection interface and re-initiate the connection, thereby avoiding continuous invalid reconnection attempts when the network is abnormal for a long time.

[0076] S6: Based on the standardized event and the reconnection stop signal, publish connection status and message data to the business layer through the unified subscription interface.

[0077] In a specific implementation, a subscription-based distribution model is first provided at the business access layer. The core of this model is a unified subscription interface. Through this unified subscription interface, two types of subscriptions are exposed to the business layer: notification message subscriptions and connection status subscriptions. The business layer does not need to care about whether the underlying platform is H5, WeChat Mini Program, or App-Plus, nor does it need to care about the details of WebSocket connection establishment, heartbeat, reconnection, etc. It only needs to register subscription callbacks through the unified subscription interface to receive messages and perceive the status.

[0078] When the business layer calls the unified subscription interface, it retrieves the subscription callback passed in by the business layer and stores it in the subscriber. The subscriber stores the subscription callbacks using the subscription callback identifier as the key. Each subscription callback includes at least a notification message subscription callback and a connection status subscription callback. The subscription callback identifier can be a string or an integer, provided by the business layer during subscription or automatically generated by the system, and is used to locate the corresponding callback function when unsubscribing.

[0079] After the subscription callback storage is complete, the corresponding publishing logic is triggered when the event in the standardized event arrives. Specifically: When the "open" event from the standardized events is received, it indicates that the connection has been successfully established. The connection status data is then published to the business layer via the connection status subscription callback. After receiving this status data, the business layer can update the connection status UI (e.g., display a "connected" icon) or execute the business logic established after the connection is established (e.g., fetch offline messages).

[0080] When the closed event from the standardized events is received, the connection status data is published to the business layer via the connection status subscription callback. After receiving the status data, the business layer can update the connection status UI (e.g., display a "disconnected" icon) or notify the user of a network error.

[0081] When an error event is received from the standardized events, the connection error status data is published to the business layer via the connection status subscription callback. After receiving the status data, the business layer can distinguish the error type (such as certificate error, server connection refusal, etc.) and provide appropriate prompts or handle the situation accordingly.

[0082] When a business message is received, it is published to the business layer via a notification message subscription callback. Business messages are specific application-layer data, such as to-do reminders, system notifications, and real-time data updates. Upon receiving a business message, the business layer executes the corresponding business logic based on the message type, such as displaying a notification pop-up on the UI, updating the to-do list, or refreshing the data display.

[0083] When a reconnection stop signal is received, the system publishes reconnection exhaustion status data to the business layer via a connection status subscription callback. Upon receiving this status data, the business layer can prompt the user with "Connection failed, please try again later" or provide a "Manual Reconnect" button, allowing the user to decide when to re-initiate the connection.

[0084] When a page or component is unloaded (e.g., during page navigation or component destruction), the unsubscribe flag passed from the business layer is retrieved, the corresponding subscription callback is removed from the subscriber, and the subscription callback ceases to receive any subsequent events and messages. This unsubscribe mechanism prevents memory leaks or state update errors caused by callback functions still being executed after a component is unloaded.

[0085] With the subscription-based distribution model described above, the business layer only needs to subscribe when the page loads and unsubscribe when the page is uninstalled to fully receive connection state changes and notification messages. This eliminates the need for scattered event-determining code across different pages or modules, significantly reducing coupling and improving maintainability. The entire subscription-based distribution process is consistent across all platforms, allowing the same business code to run seamlessly on H5, WeChat Mini Programs, and App-Plus platforms.

[0086] It is important to note that all numerical parameters in this method have basic default values. Specifically, the fixed heartbeat interval is 30,000 milliseconds, used to control the frequency of heartbeat request messages; the heartbeat timeout threshold is 60,000 milliseconds, used to determine whether the connection has lost activity due to heartbeat response timeout; the maximum reconnection delay is 30,000 milliseconds, serving as the upper limit of the waiting time in the exponential backoff reconnection strategy; the connection timeout threshold is 10,000 milliseconds, used to determine whether the connection establishment request has timed out; and the close code is 1000, used to send a standard normal close status code to the server when actively closing the connection. When any numerical parameter is detected to be non-positive or exceeds a preset boundary, the numerical parameter is reverted to its corresponding basic default value to avoid connection anomalies or system instability caused by invalid parameters.

[0087] In this embodiment, a three-level configuration merging and URL authentication pass-through are used to achieve unified access for multi-terminal connection parameters. State variables are introduced to coordinate the return order of start events and connection task objects to avoid race conditions. Local and global dual-channel event binding combined with a multi-level deduplication mechanism ensures reliable event arrival and non-duplicated distribution. Multi-format heartbeat response compatibility identification and timeout detection maintain connection activity. Exponential backoff reconnection scheduling and manual shutdown flag control are used to avoid reconnection storms. At the same time, a subscription distribution model decouples the business layer from the underlying connection logic. The combined effect of the above mechanisms enables this method to maintain consistency and stability in connection establishment, event processing, activity maintenance, and anomaly recovery behavior in multi-terminal differentiated environments, effectively reducing the complexity and maintenance cost of multi-terminal access.

[0088] like Figure 2 As shown, the following are embodiments of the cross-platform WebSocket long connection management system provided in this disclosure. This system and the cross-platform WebSocket long connection management methods in the above embodiments belong to the same inventive concept. For details not described in detail in the embodiments of the cross-platform WebSocket long connection management system, please refer to the embodiments of the cross-platform WebSocket long connection management method described above.

[0089] A cross-platform WebSocket long-connection management system, comprising: The configuration generation module is used to uniformly configure the WebSocket connection parameters of different ends, generate a standardized configuration object, and construct a connection Uniform Resource Locator based on the standardized configuration object.

[0090] The connection establishment module is used to initiate a connection based on the standardized configuration object and the connection Uniform Resource Locator, generate a current connection identifier, and process the return order of the start event and the connection task object through state variables to obtain the connection task object and the current connection identifier.

[0091] The event binding module is used to register events using a local event binding method based on the connection task object and the current connection identifier, and to obtain standardized events by deduplicating the received events using the global event interface as a backup binding channel.

[0092] The heartbeat management module is used to start the heartbeat mechanism according to the start event in the standardized events. In the heartbeat mechanism, heartbeat request messages are sent at fixed heartbeat intervals, the heartbeat response returned by the server is identified and the most recent heartbeat time is recorded, and a disconnection trigger signal is obtained when a disconnection or heartbeat timeout occurs.

[0093] The reconnection scheduling module is used to perform reconnection scheduling according to the disconnection trigger signal: in the case of non-active shutdown, the reconnection waiting time is calculated according to the exponential backoff strategy; when the number of reconnection attempts has not reached the maximum number of reconnection attempts, the connection establishment module is triggered to re-initiate the connection according to the reconnection waiting time; when the number of reconnection attempts reaches the maximum number of reconnection attempts, automatic scheduling is stopped and a reconnection stop signal is obtained.

[0094] The subscription and distribution module is used to publish connection status and message data to the business layer through a unified subscription interface based on the standardized events and the reconnection stop signal.

[0095] The cross-platform WebSocket long-connection management system provided in this embodiment unifies the handling of differences in connection establishment parameters and authentication transmission methods in multi-platform environments, enabling the same set of connection logic to run normally on H5, WeChat Mini Program, and App-Plus platforms, significantly reducing the complexity of multi-platform access. It coordinates the uncertain return order of start events and connection task objects through state variables, eliminating duplicate or missed initializations caused by race conditions during connection establishment. Through local and global dual-channel event binding and multi-level deduplication mechanisms, it ensures reliable event arrival and prevents duplicate distribution across platforms. It maintains connection activity through the compatible identification of periodic heartbeats and multi-format heartbeat responses, automatically triggering reconnection when heartbeats time out or connections fail. It controls reconnection behavior through exponential backoff reconnection strategies and manual close flags, avoiding reconnection storms while ensuring timely recovery after disconnection. The combined effect of these mechanisms enables the system to maintain consistency and stability in connection establishment, event handling, activity maintenance, and anomaly recovery behavior in multi-platform differentiated environments, while decoupling the business layer from the underlying connection logic, significantly reducing maintenance costs.

[0096] Figure 3 A schematic diagram of the hardware structure of an electronic device for implementing various embodiments of the present invention.

[0097] The cross-platform WebSocket long connection management method provided in this application can be applied to electronic devices. Those skilled in the art will understand that the electronic device structure involved in the embodiments of this invention does not constitute a limitation on the electronic device. An electronic device may include more or fewer components than illustrated, or combine certain components, or have different component arrangements. In the embodiments of this invention, the electronic device includes, but is not limited to, laptop computers, desktop computers, workstations, personal digital assistants, servers, blade servers, mainframe computers, and other suitable computers. The electronic device may also represent various forms of mobile devices, such as personal digital processors, cellular phones, smartphones, wearable devices, and other similar computing devices. The components shown herein, their connections and relationships, and their functions are merely examples and are not intended to limit the implementation of the embodiments of this application described and / or claimed herein.

[0098] Electronic devices may include processors, external memory interfaces, internal memory, universal serial bus (USB) interfaces, charging management modules, power management modules, batteries, wireless communication modules, audio modules, speakers, microphones, sensor modules, buttons, cameras, displays, and SIM card interfaces, etc.

[0099] A processor may include one or more processing units, such as: a central processing unit (CPU), an application processor (AP), a modem processor, a graphics processing unit (GPU), an image signal processor (ISP), a controller, memory, a video codec, a digital signal processor (DSP), a baseband processor, and / or a neural network processing unit (NPU). Different processing units may be independent devices or integrated into one or more processors.

[0100] The processor can serve as the nerve center and command center of an electronic device. The controller can generate operation control signals based on the instruction opcode and timing signals to control the fetching and execution of instructions.

[0101] The processor may also include memory for storing instructions and data. In some embodiments, the memory in the processor is a cache memory. This memory can store instructions or data that the processor has just used or that are used repeatedly. If the processor needs to use the instruction or data again, it can retrieve it directly from this memory. This avoids repeated accesses, reduces processor latency, and thus improves system efficiency.

[0102] An external storage interface (ESI) can be used to connect external memory cards, such as microSD cards, to expand the storage capacity of electronic devices. The external memory card communicates with the processor through the ESI to perform data storage functions, such as saving music and video files on the external memory card.

[0103] Internal memory can be used to store computer executable program code, which includes instructions. The processor executes various functional applications and data processing of electronic devices by running the instructions stored in internal memory. Internal memory can include a program storage area and a data storage area. Internal memory can include high-speed random access memory, and can also include non-volatile memory, such as at least one disk storage device, flash memory device, universal flash storage (UFS), etc.

[0104] Wireless communication functionality in electronic devices can be achieved through antennas, wireless communication modules, modem processors, and baseband processors.

[0105] Wireless communication modules can provide solutions for wireless communication applications in electronic devices, including wireless local area networks (WLANs) (such as wireless fidelity (Wi-Fi) networks), Bluetooth (BT), global navigation satellite system (GNSS), frequency modulation (FM), near field communication (NFC), and infrared (IR) technologies.

[0106] Electronic devices can implement audio functions through audio modules, speakers, receivers, microphones, headphone jacks, and application processors.

[0107] Electronic devices can achieve shooting functions through ISPs, cameras, video codecs, GPUs, displays, and application processors.

[0108] Electronic devices can achieve display functions through GPUs, displays, and application processors.

[0109] A GPU is a microprocessor for image processing, connected to the display screen and application processor. GPUs are used to perform mathematical and geometric calculations for graphics rendering. A processor may include one or more GPUs, which execute program instructions to generate or modify display information.

[0110] A display screen is used to display images, videos, etc. A display screen includes a display panel.

[0111] The aforementioned electronic device implements the cross-terminal WebSocket long connection management method of this application, which achieves the beneficial effects of consistent cross-terminal connection behavior, reliable event arrival, and robust reconnection after disconnection through unified configuration of multi-terminal connection establishment, connection race state coordination, dual-channel event binding, and exponential backoff reconnection.

[0112] The storage medium provided in this application stores a program product capable of implementing a cross-platform WebSocket long connection management method.

[0113] In some possible implementations, the cross-terminal WebSocket long connection management method of this disclosure can be implemented as a program product that includes program code that, when the program product is run on a terminal device, causes the terminal device to perform the steps described in the "Exemplary Methods" section above according to various exemplary embodiments of this disclosure.

[0114] The storage medium disclosed herein may be any combination of one or more readable media. A readable medium may be a readable signal medium or a readable storage medium. A readable storage medium may be, for example, but not limited to, an electrical, magnetic, optical, electromagnetic, infrared, or semiconductor system, apparatus, or device, or any combination thereof. More specific examples (a non-exhaustive list) of readable storage media include: an electrical connection having one or more wires, a portable disk, a hard disk, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fiber, portable compact disk read-only memory (CD-ROM), optical storage device, magnetic storage device, or any suitable combination thereof.

[0115] The above description of the disclosed embodiments enables those skilled in the art to make or use the invention. Various modifications to these embodiments will be readily apparent to those skilled in the art, and the general principles defined herein may be implemented in other embodiments without departing from the spirit or scope of the invention. Therefore, the invention is not to be limited to the embodiments shown herein, but is to be accorded the widest scope consistent with the principles and novel features disclosed herein.

Claims

1. A cross-platform WebSocket long connection management method, characterized in that, Includes the following steps: S1: Configure the WebSocket connection parameters for different ends in a unified manner, generate a standardized configuration object, and construct a connection Uniform Resource Locator based on the standardized configuration object; S2: Initiate a connection based on the standardized configuration object and the connection Uniform Resource Locator, generate a current connection identifier, and process the return order of the start event and the connection task object through state variables to obtain the connection task object and the current connection identifier; S3: Based on the connection task object and the current connection identifier, register the event using the local event binding method, and use the global event interface as a backup binding channel to deduplicate the received events to obtain standardized events; S4: Start the heartbeat mechanism according to the start event in the standardized event. In the heartbeat mechanism, heartbeat request messages are sent at fixed heartbeat intervals. The heartbeat response returned by the server is identified and the most recent heartbeat time is recorded. A disconnection trigger signal is obtained when a disconnection or heartbeat timeout occurs. S5: Perform reconnection scheduling according to the disconnection trigger signal: In the case of non-active shutdown, calculate the reconnection waiting time according to the exponential backoff strategy. When the number of reconnection attempts has not reached the maximum number of reconnection attempts, re-execute step S2 according to the reconnection waiting time. When the number of reconnection attempts reaches the maximum number of reconnection attempts, stop automatic scheduling and obtain a reconnection stop signal. S6: Based on the standardized event and the reconnection stop signal, publish connection status and message data to the business layer through the unified subscription interface.

2. The cross-platform WebSocket long connection management method according to claim 1, characterized in that, Step S1 includes: The system obtains three types of configuration sources: basic configuration objects, general overlay configuration objects, and client-specific overlay configuration objects. The basic configuration object contains protocol fields, host fields, path fields, connection timeout fields, and close code fields. The general overlay configuration object contains protocol overlay fields, host overlay fields, path overlay fields, connection timeout fields, and close code overlay fields. The client-specific overlay configuration objects correspond to H5 client, WeChat mini-program client, and mobile App-Plus client, respectively. Each client-specific overlay configuration object contains protocol fields, host fields, path fields, connection timeout fields, close code fields, and global fallback enable fields. Using the basic configuration object, the general coverage configuration object, and the terminal-specific coverage configuration object as input, and following the priority order of terminal-specific coverage configuration object > general coverage configuration object > basic configuration object, the protocol field, host field, path field, connection timeout field, and close code field are merged at the field level: For each field, a non-empty value of the field in the terminal-specific coverage configuration object is taken; if the field in the terminal-specific coverage configuration object is empty or does not exist, a non-empty value of the field in the general coverage configuration object is taken; if the field in the general coverage configuration object is empty or does not exist, the non-empty value of the field in the general coverage configuration object is taken. If the value is not null, then the non-null value of the field in the basic configuration object is taken, and the result is used as the value of the corresponding field in the standardized configuration object to generate a standardized configuration object. Specifically, if the host field of the H5 side is null, then the host address of the current page is obtained as the value of the host field in the standardized configuration object. If the protocol field is not explicitly overridden, then wss or ws is taken as the value of the protocol field in the standardized configuration object according to whether the current page protocol type is HTTPS or HTTP. If the path field is null, then the default path is taken as the value of the path field in the standardized configuration object, and the default path is / web-link / publish. Obtain the Authorization and clientid parameters from the authentication information passed in from the business layer. Perform URL encoding on the Authorization and clientid parameters respectively and then concatenate them into the query parameter field. Concatenate the protocol field, host field, path field and query parameter field in the standardized configuration object in sequence to generate a connection Uniform Resource Locator.

3. The cross-platform WebSocket long connection management method according to claim 2, characterized in that, Step S2 includes: Based on the standardized configuration object and the connection Uniform Resource Locator, a connection timeout threshold is set, and a connection request is initiated, wherein the connection timeout threshold is set according to the connection timeout field in the standardized configuration object; The following state variable initialization process is executed: Initialize the current connection identifier to the identifier value of this connection, initialize the connection identifier with processed open events to null, initialize the open wait flag to false, initialize the manual close flag to false, initialize the socket task object to null, initialize the socket commitment object to null, initialize the reconnection attempt count to 0, initialize the reconnection timer to null, initialize the connection identifier with processed close events to null, and initialize the subscriber to null. The current connection identifier is incremented and used as the current connection identifier for this connection. Listen for the return of the start event and the connection task object; if the start event returns before the connection task object, assign the connection identifier of the processed start event to the current connection identifier, and set the start waiting flag to true when the socket task object is not ready, waiting for the socket task object to return; if the connection task object returns before the start event, temporarily store the connection task object in the socket task object, waiting for the start event to be triggered. After the connection task object returns, the following judgment is performed based on the connection task object, the start-up waiting flag, the connection identifier of the processed start-up event, and the current connection identifier: If the start-up waiting flag is true, the connection identifier of the processed start-up event is equal to the current connection identifier, and the connection task object is not empty, then the pending start-up initialization logic is executed, the heartbeat mechanism is started, and the current connection identifier and the connection task object are obtained; if the start-up event is received repeatedly when the connection identifier of the processed start-up event is equal to the current connection identifier, then the repeated start-up event is ignored.

4. The cross-platform WebSocket long connection management method according to claim 3, characterized in that, Step S3 includes: Detect the current endpoint environment type based on the connection task object and the current connection identifier; Select the corresponding local event binding method according to the terminal environment type, and register start event, message event, error event and close event for the connection task object; According to the global fallback enable field in the standardized configuration object, when the global fallback enable field indicates that there is a risk of local event binding being unreachable, a global event interface is registered as a backup binding channel, and the same current connection identifier is registered only once for the global event interface; For start events, message events, error events, and close events arriving via local event binding or global event interface, deduplication is performed: For start events, the current connection identifier is compared with the connection identifier of a previously processed start event; if they match, the start event is discarded; otherwise, a deduplicated start event is obtained. For close events, the current connection identifier is compared with the connection identifier of a previously processed close event; if they match, the close event is discarded; otherwise, the connection identifier of the previously processed close event is assigned to the current connection identifier, and a deduplicated close event is obtained. For error events, the current connection identifier is compared with the connection identifier of a processed closure event. If they match, the error event is discarded; otherwise, the connection identifier of the processed closure event is assigned to the current connection identifier, resulting in a deduplicated error event. For message events, the message identifier or notification identifier is extracted as a key. The recent message identifier set is queried. If the key already exists in the recent message identifier set, the message event is discarded; otherwise, the key is added to the recent message identifier set, resulting in a deduplicated message event. The deduplicated open event, deduplicated message event, deduplicated error event, and deduplicated close event are treated as standardized events.

5. The cross-platform WebSocket long connection management method according to claim 4, characterized in that, Step S4 includes: According to the enable event in the standardized event, the heartbeat mechanism is started, specifically including: when the enable event in the standardized event arrives, a heartbeat timer is started according to the fixed heartbeat interval, and a heartbeat request message is periodically sent through the connection at the fixed heartbeat interval, wherein the heartbeat request message is the string "ping"; Obtain the raw response data returned by the connection, and perform compatibility recognition on the heartbeat response returned by the server: check if the raw response data is the string "pong", if so, it is recognized as a heartbeat response; if the raw response data is a JSON format message, extract the values ​​of the cmd field, type field, event field and raw field in the JSON format message in sequence, and match the value of each field with the string "pong" or "ping". If the value of any field matches the string "pong" or "ping", it is recognized as a heartbeat response; If the response is identified as a heartbeat, the current system time is obtained and the most recent heartbeat time is written. The heartbeat identifier is extracted and recorded. If the response is not identified as a heartbeat, the original response data is treated as a business message. Based on the most recent heartbeat time and the current system time, calculate the difference between the current system time and the most recent heartbeat time. If the difference is greater than the heartbeat timeout threshold, actively close the current connection and keep the manual close flag false to obtain a disconnection trigger signal.

6. The cross-platform WebSocket long connection management method according to claim 5, characterized in that, Step S5 includes: Obtain the manual shutdown flag, obtain the current reconnection attempt count, and determine the maximum reconnection delay and maximum reconnection attempt count from the standardized configuration object; If the manual shutdown flag is true, then reconnection scheduling is prohibited and the process is terminated; If the manual close flag is false, the scheduling queue is represented by a unique reconnection timer. The status of the reconnection timer is queried: if the reconnection timer is not empty, new reconnection tasks are rejected from being enqueued and the process is terminated; if the reconnection timer is empty, the current reconnection attempt count is incremented according to... Calculate the reconnection waiting time, where Indicates the first Reconnection wait time after the first failure This is the current reconnection attempt count after incrementing. The reconnection waiting time is set as a delay parameter for the reconnection timer. After the reconnection timer is triggered, the reconnection timer is cleared first. The current number of reconnection attempts after clearing is obtained, and the maximum number of reconnection attempts is obtained. If the current reconnection attempt count after clearing does not reach the maximum reconnection attempt count, then based on the standardized configuration object and the connection unified resource locator, jump to step S2 to re-initiate the connection; if the current reconnection attempt count after clearing reaches the maximum reconnection attempt count, then stop automatic scheduling and obtain a reconnection stop signal; Once the connection is successfully established and enters the open state, the number of reconnection attempts is reset to zero. Once the service actively closes the connection or the authentication information changes, the number of reconnection attempts is reset to zero. When the manual close flag is true, the reconnection timer is canceled and the jump to step S2 is prohibited.

7. The cross-platform WebSocket long connection management method according to claim 6, characterized in that, Step S6 includes: A subscription-based distribution model is provided at the business access layer, and notification message subscription and connection status subscription are made available to the business layer through a unified subscription interface; When the business layer calls the unified subscription interface, it obtains the subscription callback passed by the business layer and stores it in the subscriber. The subscriber stores the subscription callback with the subscription callback identifier as the key. The subscription callback includes at least the notification message subscription callback and the connection status subscription callback. When the open event in the standardized event is obtained, the connection is published to the business layer through the connection state subscription callback; when the close event in the standardized event is obtained, the connection is published to the business layer through the connection state subscription callback; when the error event in the standardized event is obtained, the connection error is published to the business layer through the connection state subscription callback. When the business message is obtained, the business message is published to the business layer through the notification message subscription callback; When the reconnection stop signal is received, the reconnection status data that has been exhausted is published to the business layer through the connection status subscription callback; When a page or component unload signal is received, the unsubscribe flag passed from the business layer is obtained, the corresponding subscription callback is removed from the subscriber, and the subscription callback is terminated from receiving any subsequent events and messages.

8. A cross-platform WebSocket long-connection management system, characterized in that, The system employs the cross-platform WebSocket long connection management method as described in any one of claims 1 to 7; The system includes: The configuration generation module is used to uniformly configure the WebSocket connection parameters of different ends, generate a standardized configuration object, and construct a connection Uniform Resource Locator based on the standardized configuration object; The connection establishment module is used to initiate a connection based on the standardized configuration object and the connection Uniform Resource Locator, generate a current connection identifier, and process the return order of the start event and the connection task object through state variables to obtain the connection task object and the current connection identifier. The event binding module is used to register events using a local event binding method based on the connection task object and the current connection identifier, and to use the global event interface as a backup binding channel to deduplicate the received events to obtain standardized events. The heartbeat management module is used to start the heartbeat mechanism according to the start event in the standardized event. In the heartbeat mechanism, heartbeat request messages are sent at fixed heartbeat intervals, the heartbeat response returned by the server is identified and the most recent heartbeat time is recorded, and a disconnection trigger signal is obtained when a disconnection or heartbeat timeout occurs. The reconnection scheduling module is used to perform reconnection scheduling according to the disconnection trigger signal: in the case of non-active shutdown, the reconnection waiting time is calculated according to the exponential backoff strategy; when the number of reconnection attempts has not reached the maximum number of reconnection attempts, the connection establishment module is triggered to re-initiate the connection according to the reconnection waiting time; when the number of reconnection attempts reaches the maximum number of reconnection attempts, automatic scheduling is stopped and a reconnection stop signal is obtained. The subscription and distribution module is used to publish connection status and message data to the business layer through a unified subscription interface based on the standardized events and the reconnection stop signal.

9. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the program, it implements the steps of the cross-platform WebSocket long connection management method as described in any one of claims 1 to 7.

10. A storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by a processor, it implements the steps of the cross-platform WebSocket long connection management method as described in any one of claims 1 to 7.