A WebSocket connection management method and system based on a security waiting window

CN122845641APending Publication Date: 2026-09-29HENAN INFORMATIZATION GRP CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611113010.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-25
Publication Date
2026-09-29

AI Technical Summary

Technical Problem

[0003]传统WebSocket实现方案缺乏对网络环境的感知能力,往往采用无限次重试或固定频率重试,在网络长期不可用或服务端故障时,客户端会发起无效的重连风暴,导致移动端电量急剧消耗、CPU占用过高,甚至触发服务端的IP封禁策略;

Benefits of technology

1、本发明通过引入“安全等待窗口”机制,强制等待底层资源完全释放后再建立新连接,彻底消除因异步回调滞后导致的状态误判和重连误触发,实现用户无感知的平滑连接迁移;

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122845641A_ABST
    Figure CN122845641A_ABST
Patent Text Reader

Abstract

This invention discloses a WebSocket connection management method and system based on a secure wait window, specifically relating to the field of computer network communication technology. It includes a mobile terminal and a connection management server. The mobile terminal runs a cross-platform hybrid application based on JSBridge and includes a local rule parser and an instruction cache queue. The connection management server includes a global state management module for managing connection instances in a singleton pattern and constructing a WebSocket Uniform Resource Locator containing secure encoding parameters. This invention introduces a secure wait window mechanism, forcing the establishment of a new connection only after the underlying resources are completely released, thus completely eliminating misjudgments of state and accidental reconnection triggers caused by asynchronous callback lag, achieving a smooth connection migration that is imperceptible to the user. Based on the organic combination of multi-dimensional state flags and network awareness, it ensures that reconnection only occurs when necessary and conditions permit, reducing invalid reconnection requests by more than 70%.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer network communication technology, and more specifically, to a WebSocket connection management method and system based on a secure waiting window. Background Technology

[0002] With the continuous iteration and development of mobile Internet technology, the application scenarios of mobile devices such as smartphones and portable smart terminals are constantly expanding. Low-latency two-way interactive applications such as instant messaging, real-time push of business status, synchronization of device operation data, and real-time reporting of dynamic information for mobile terminals have been widely adopted and implemented. WebSocket, as a full-duplex two-way communication protocol built on TCP, can establish a persistent long-term connection channel between the client and the server. After the connection is established, both parties can autonomously and proactively complete the two-way real-time sending and receiving of data without being restricted by the request time sequence, effectively reducing communication latency and network resource consumption.

[0003] Traditional WebSocket implementations lack awareness of the network environment and often use infinite retries or fixed-frequency retries. When the network is unavailable for a long time or the server fails, the client will launch an invalid reconnection storm, which will cause the mobile device to consume battery power rapidly, CPU usage to be too high, and even trigger the server's IP blocking policy. Secondly, when the dynamic address is updated, the existing technology ignores the lag of the underlying asynchronous callback, directly closes the old connection and immediately establishes a new connection, resulting in the temporary coexistence of the old and new connections; the lagging onClose callback of the old connection may be misjudged as an abnormal disconnection, thus incorrectly triggering reconnection based on the old parameters, causing message interference, data pollution and memory leaks. Summary of the Invention

[0004] To achieve the above objectives, the present invention provides the following technical solution: a WebSocket connection management system based on a secure waiting window, comprising a mobile terminal and a connection management server, wherein the mobile terminal is used to run a cross-platform hybrid application based on JSBridge, including a local rule parser and an instruction cache queue; The connection management server includes: a global state management module, used to manage connection instances in singleton mode, construct a WebSocket Uniform Resource Locator containing security encoding parameters, and maintain the global connection state; The core communication module encapsulates the native WebSocket interface and is responsible for underlying connection establishment, closing, reconnection scheduling, and end-to-end exception handling. The business event distribution module, based on the event bus mechanism, is used to route data to the corresponding business processing unit according to the message type. The core communication module includes: The status flag register is used to store connection status flags, including at least the manual close flag (isManuallyClosed). The safe wait window timer is used to create an asynchronous delay timer with a preset duration during dynamic address updates, in order to build a safe wait window for resource release.

[0005] Furthermore, the local rule parser stores a pre-loaded simplified rule base, which contains a set of frequently triggered IF-THEN rules, which are automatically generated and updated by the connection management server based on recent high-frequency linkage rules.

[0006] Furthermore, the communication core module also includes a reconnection scheduler, which is used to execute or prevent reconnection operations based on the flag bits in the status flag register and the preset reconnection policy. The reconnection policy includes: reconnection logic is only allowed to be triggered when isManuallyClosed is false, the connection is not established, and the number of consecutive reconnections is less than the preset maximum reconnection number threshold.

[0007] Furthermore, when the number of consecutive reconnection failures reaches the preset maximum reconnection count threshold, the reconnection scheduler stops reconnecting and releases all related resources, while simultaneously issuing a network anomaly notification through the service event distribution module.

[0008] Furthermore, the reconnection scheduler is also used to monitor system network status change events. When it detects that the network has recovered from unavailable to available and the reconnection triggering conditions are met, it immediately initiates a reconnection request.

[0009] Furthermore, the core communication module also includes an exception capture container, which is used to capture exceptions at each stage of message reception, data parsing, and callback execution. When parsing a single message fails, it only discards the current exception message and records the error log, without interrupting the lifecycle of the WebSocket main connection.

[0010] Furthermore, when generating the WebSocket Uniform Resource Locator, the global state management module forces the authentication credential parameters to be percentage-encoded.

[0011] This invention also provides a WebSocket connection management method based on a secure wait window, applied to the aforementioned WebSocket connection management system based on a secure wait window, comprising the following steps: S1. Connection Establishment: The global state management module securely encodes the authentication credential and generates a URL, and the communication core module establishes the connection. S2, Status Control: The communication core module maintains a status flag register and determines the disconnection type based on the manually turned-off flag. S3, Intelligent Reconnection: When an abnormal disconnection that is not actively closed is detected, the reconnection scheduler triggers reconnection according to the preset reconnection strategy. S4. Dynamic Address Update: When a new authentication credential is received, the following sub-steps are executed: S4-1. Manually turn off the flag and clear all reconnection timers; S4-2. Close the current WebSocket connection; S4-3. Start the safety wait window timer and wait for the preset duration; S4-4. After the timer expires, reset the manual close flag and establish a new connection using the new credentials; S5. Exception Capture and Closed-Loop Feedback: The exception capture container captures and processes local exceptions, and sends execution feedback through the business event distribution module.

[0012] Furthermore, the method for determining the preset duration in step S4-3 includes: static configuration based on the target platform pre-test results, or dynamic calculation—maintaining a historical shutdown delay queue and calculating the preset duration = max(historical delay) × safety factor, where the safety factor ≥ 1.2.

[0013] Furthermore, the reconnection strategy described in step S3 includes: the maximum reconnection count threshold is 10 times by default, the reconnection interval adopts the exponential backoff algorithm, the initial delay is 2 seconds, and the delay is doubled each time thereafter until the maximum delay is 30 seconds.

[0014] The technical effects and advantages of this invention are as follows: 1. This invention introduces a "safe waiting window" mechanism, which forces the establishment of a new connection only after the underlying resources are completely released, thus completely eliminating misjudgment of the status and false triggering of reconnection caused by asynchronous callback lag, and achieving a smooth connection migration that is imperceptible to the user. 2. Based on the organic combination of multi-dimensional status flag bits and network awareness, this invention ensures that reconnection only occurs when necessary and conditions permit, reduces invalid reconnection requests by more than 70%, reduces connection resource consumption by about 30%, effectively avoids reconnection storms, and extends the battery life of mobile devices. 3. This invention separates connection management, state synchronization and business processing through a three-layer architecture, reducing maintenance costs by more than 50%; mandatory parameter encoding eliminates injection risks; and end-to-end anomaly capture ensures that single-point failures do not spread, with application crash rates approaching zero. Attached Figure Description

[0015] The structures, proportions, sizes, etc. illustrated in this specification are only for the purpose of assisting those skilled in the art in understanding and reading the content disclosed herein, and are not intended to limit the conditions under which the present invention can be implemented. Therefore, they have no substantial technical significance. Any modifications to the structure, changes in the proportions, or adjustments to the size, without affecting the effects and objectives that the present invention can produce, should still fall within the scope of the technical content disclosed in the present invention.

[0016] Figure 1 This is a system module diagram of the present invention; Figure 2 This is a flowchart of the method of the present invention.

[0017] In the picture: 100. Mobile terminal; 101. Local rule parser; 102. Instruction cache queue; 200. Connection Management Server; 201. Global Status Management Module; 202. Communication Core Module; 2021. Status Flag Register; 2022. Reconnection Scheduler; 2023. Security Waiting Window Timer; 2024. Exception Capture Container; 203. Business Event Distribution Module. Detailed Implementation

[0018] The following specific embodiments illustrate the implementation of the present invention. Those skilled in the art can easily understand other advantages and effects of the present invention from the content disclosed in this specification. Obviously, the described embodiments are only some, not all, of the embodiments of the present invention. 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.

[0019] Example 1 Refer to the instruction manual appendix Figure 1 This embodiment of a WebSocket connection management system based on a secure waiting window includes a mobile terminal 100 and a connection management server 200. The mobile terminal 100 is deployed on a user device and has a hybrid application developed based on UniApp installed on it; the connection management server 200 is deployed on the application server.

[0020] When a user logs into the app for the first time, the application reads the user's authentication token from local secure storage. The global state management module 201 calls its internal buildWsUrl method, which forces the token parameter to be percent-encoded using encodeURIComponent to prevent special characters (such as &, ?, #, etc.) from corrupting the URL structure or causing injection attacks, generating a secure WebSocket connection address in the form of wss: / / api.example.com / ws?token=eyJhbGc...

[0021] Subsequently, the communication core module 202 instantiates a WsClient object and calls its connect() method. This method internally calls the UniApp's uni.connectSocket interface to create a SocketTask instance and registers callback functions such as onOpen, onMessage, onClose, and onError. After the connection is successfully established, the isConnected flag in the status flag register 2021 is set to true. At the same time, the communication core module 202 publishes the connection success event through the business event distribution module 203. Each business module (such as the market data page) subscribes to the event and updates the UI to display "Real-time market data has been connected". When a user enters the elevator with a mobile terminal 100, the network signal is completely interrupted. At this time, the underlying TCP connection of WebSocket is passively disconnected, and the system triggers the onClose callback. The communication core module 202 first sets isConnected to false, and then reads the isManuallyClosed flag in the status flag register 2021. Since this disconnection was a passive disconnection caused by network issues, rather than a user logout or an application actively calling to close the interface, isManuallyClosed is false. The reconnect scheduler 2022 is woken up and checks whether reconnectCount is less than the preset maximum reconnection count threshold (10 times in this embodiment). If it is less than 1, then reconnectCount will be incremented by 1, and the reconnection timer will be started using the exponential backoff algorithm: the first reconnection will be delayed by 2 seconds, the second by 4 seconds, the third by 8 seconds, and so on, with a maximum delay of no more than 30 seconds; Meanwhile, the reconnect scheduler 2022 listens for network status change events of mobile devices (such as onNetworkStatusChange) through the system API. If the network recovers from "unavailable" to "available" during the reconnection waiting period, the currently waiting reconnection timer is immediately canceled and the reconnect() method is immediately executed to restore the connection as quickly as possible. If 10 consecutive reconnections fail, the reconnection scheduler 2022 stops all reconnection attempts, releases all system resources associated with the connection (such as timers and callback references), and publishes a "Network error, please check network connection" event to the UI layer through the business event distribution module 203, prompting the user to intervene manually. In the message receiving phase, the exception capture container 2024 of the communication core module 202 uses a try-catch block to wrap the JSON.parse parsing operation in the onMessage callback. When a single message sent by the server has an incorrect format (such as an invalid JSON string), the parsing exception is caught. The system only records the error to the local log (including the original data and timestamp) and discards the message. The main connection continues to be maintained, and other normal messages can still be correctly parsed and distributed. For exceptions caught in the onError callback (such as underlying Socket read / write errors), only logs are recorded, without interrupting the state machine management of the connection, thus preventing application crashes.

[0022] Example 2 Refer to the instruction manual appendix Figure 2 Based on Example 1, this example provides a WebSocket connection management method based on a secure waiting window: S1. Connection Establishment: The global state management module 201 securely encodes the authentication credential and generates a URL, and the communication core module 202 establishes the connection. S2, Status Control: The communication core module 202 maintains the status flag register 2021 and determines the disconnection type based on the manually turned-off flag. S3, Intelligent Reconnection: When an abnormal disconnection that is not actively closed is detected, the reconnection scheduler 2022 triggers reconnection according to the preset reconnection strategy; S4. When the user's authentication credential is about to expire, the application backend automatically requests a new Token from the server. After obtaining the newToken, the global state management module 201 calls the updateUrl(newToken) method of the communication core module 202, triggering the following atomic operation sequence: Step S4-1 (Blocking Flag): Set the isManuallyClosed flag in the status flag register 2021 to true; simultaneously call the clearAllTimers method of the reconnection scheduler 2022 to clear all pending reconnection timers. This step ensures that any subsequent callbacks of the old connection (including delayed onClose) will not trigger the reconnection logic.

[0023] Step S4-2 (Close the old connection): Call the close() method of the current SocketTask object to initiate a request to close the old WebSocket connection. The native layer begins to asynchronously destroy underlying resources such as TCP sockets, file descriptors, and event listeners. Step S4-3 (Safety Waiting Window): Start the safety waiting window timer 2023, with a preset duration of T. In this embodiment, T is determined by dynamic calculation: The communication core module 202 maintains a circular queue closeDelayHistory of length 10 to record the actual time (in milliseconds) from the call to close() to the triggering of the onClose callback in the last 10 closing operations. When it is necessary to dynamically update the address, calculate T = max(closeDelayHistory) × 1.5, that is, take the maximum historical delay multiplied by the safety factor of 1.5. If there are fewer than 10 historical records, a static default value of 50ms will be used (this value is derived from pre-test statistics on mainstream iOS / Android models); for example, if the current historical queue is [30, 32, 28, 35, 33, 31, 29, 34, 32, 30], and the maximum value is 35ms, then T = 35 × 1.5 = 52.5ms, which is rounded up to 53ms; During the safe waiting window (within 53ms), if an old connection generates a delayed onClose callback, since isManuallyClosed is still true, the callback will return directly without performing any reconnection operation. This mechanism physically isolates the timing conflict between the release of old connection resources and the establishment of new connections; Step S4-4 (Reset and Rebuild): After the safe wait window timer 2023 expires, execute the callback: reset isManuallyClosed to false, clear reconnectCount to zero, then obtain a new token (newToken) from the global state management module 201, call buildWsUrl to generate a new URL with secure encoding, and finally call the connect() method to establish a brand new WebSocket connection. The entire dynamic address update process takes about 53ms, which is completely imperceptible to the user. The market data push is seamlessly switched, which completely solves the problems of coexistence of old and new connections, message interference and memory leaks caused by asynchronous callback lag in the existing technology. The local rule parser 101 and instruction cache queue 102 in the mobile terminal 100 provide offline fault tolerance for this system. When the mobile device is in an area with no network coverage (such as an underground parking garage), the network unavailable state continues. The local rule parser 101 stores a pre-loaded simplified rule base. This rule base is automatically generated by the connection management server 200 based on the system's high-frequency reconnection behavior during the most recent network connection (e.g., "If the number of reconnection failures is ≥3, stop reconnecting and prompt the user"). When the network is disconnected, the local rule parser 101 makes local decisions based on this rule base to avoid the mobile terminal 100 repeatedly initiating invalid reconnection requests in areas without signal, thereby saving power. Meanwhile, the instruction cache queue 102 adopts a first-in-first-out (FIFO) queue structure to temporarily store messages to be sent by users during offline periods (such as market query instructions entered by users). Each message records the generation timestamp and message ID when it is enqueued. Once the network is restored, the instruction cache queue 102 automatically retrieves messages from the queue one by one in sequence, sends them to the server through the newly established WebSocket connection, and waits for the server's confirmation response. For messages that fail to be sent, a limited number of retries (default 3 times) are performed according to a preset strategy to ensure reliable transmission of business data. The system and method described in this embodiment were tested in a typical mobile environment, and the results are as follows: During the dynamic address update process, the number of new and old connection conflict events was 0; In reconnection storm scenarios, invalid reconnection requests are reduced by approximately 72%; mobile standby power consumption is reduced by approximately 28% compared to traditional solutions; and the application crash rate caused by a single abnormal message is reduced from approximately 0.5% in traditional solutions to 0. The above data fully demonstrate the technical effectiveness of the present invention.

[0024] All contents not described in detail in the specification are existing technologies known to those skilled in the art. The above are merely preferred embodiments of the present invention and are not intended to limit the present invention. Any modifications, equivalent substitutions, and improvements made within the spirit and principles of the present invention should be included within the protection scope of the present invention.

Claims

1. A WebSocket connection management system based on a secure waiting window, characterized in that: It includes a mobile terminal (100) and a connection management server (200), the mobile terminal (100) being used to run a cross-platform hybrid application based on JSBridge, including a local rule parser (101) and an instruction cache queue (102). The connection management server (200) includes: a global state management module (201), which manages connection instances in singleton mode, constructs a WebSocket Uniform Resource Locator containing security encoding parameters, and maintains the global connection state; The communication core module (202) is used to encapsulate the native WebSocket interface and is responsible for the underlying connection establishment, closing, reconnection scheduling and end-to-end exception capture. The business event distribution module (203) is based on the event bus mechanism and is used to route data to the corresponding business processing unit according to the message type. The communication core module (202) includes: The status flag register (2021) is used to store connection status flags, including at least the manual close flag (isManuallyClosed). The Secure Wait Window Timer (2023) is used to create an asynchronous delay timer with a preset duration during dynamic address updates to build a secure wait window for resource release.

2. The WebSocket connection management system based on a secure waiting window according to claim 1, characterized in that: The local rule parser (101) stores a pre-loaded simplified rule base, which contains a set of frequently triggered IF-THEN rules, which are automatically generated and pushed for updates by the connection management server (200) based on recent frequent linkage rules.

3. The WebSocket connection management system based on a secure waiting window according to claim 1, characterized in that: The communication core module (202) also includes a reconnection scheduler (2022), which is used to execute or prevent reconnection operations according to the flag bits in the status flag register (2021) and the preset reconnection policy. The reconnection policy includes: reconnection logic is only allowed to be triggered when isManuallyClosed is false, the connection is not established and the number of consecutive reconnections is less than the preset maximum number of reconnections threshold.

4. The WebSocket connection management system based on a secure waiting window according to claim 3, characterized in that: When the number of consecutive reconnection failures reaches the preset maximum reconnection count threshold, the reconnection scheduler (2022) stops reconnection and releases all related resources, and at the same time issues a network anomaly notification through the service event distribution module (203).

5. The WebSocket connection management system based on a secure waiting window according to claim 3, characterized in that: The reconnection scheduler (2022) is also used to monitor system network status change events. When it detects that the network has recovered from unavailable to available and the reconnection triggering conditions are met, it immediately initiates a reconnection request.

6. The WebSocket connection management system based on a secure waiting window according to claim 1, characterized in that: The communication core module (202) also includes an exception capture container (2024), which is used to capture exceptions at each stage of message reception, data parsing and callback execution. When parsing a single message fails, it only discards the current exception message and records the error log, without interrupting the life cycle of the WebSocket main connection.

7. The WebSocket connection management system based on a secure waiting window according to claim 1, characterized in that: When generating a WebSocket Uniform Resource Locator, the global state management module (201) forces the authentication credential parameters to be percentage encoded.

8. A WebSocket connection management method based on a secure wait window, applied to the WebSocket connection management system based on a secure wait window as described in any one of claims 1-7, characterized in that: Includes the following steps: S1. Connection establishment: The global state management module (201) securely encodes the authentication credential and generates a URL, and the communication core module (202) establishes the connection; S2, Status Control: The communication core module (202) maintains the status flag register (2021) and determines the disconnection type based on the manually turned-off flag; S3, Intelligent Reconnection: When an abnormal disconnection that is not actively closed is detected, the reconnection scheduler (2022) triggers reconnection according to the preset reconnection strategy; S4. Dynamic Address Update: When a new authentication credential is received, the following sub-steps are executed: S4-1. Manually turn off the flag and clear all reconnection timers; S4-2. Close the current WebSocket connection; S4-3, Start the safety wait window timer (2023), and wait for the preset duration; S4-4. After the timer expires, reset the manual close flag and establish a new connection using the new credentials; S5. Exception capture and closed-loop feedback: The exception capture container (2024) captures and processes local exceptions and sends execution feedback through the business event distribution module (203).

9. The WebSocket connection management method based on a secure waiting window according to claim 8, characterized in that: The method for determining the preset duration in step S4-3 includes: static configuration based on the target platform pre-test results, or dynamic calculation—maintaining a historical shutdown delay queue and calculating the preset duration = max(historical delay) × safety factor, where the safety factor ≥ 1.

2.

10. The WebSocket connection management method based on a secure waiting window according to claim 8, characterized in that: The reconnection strategy described in step S3 includes: the maximum reconnection count threshold is 10 times by default, the reconnection interval adopts the exponential backoff algorithm, the initial delay is 2 seconds, and the delay is doubled each time thereafter until the maximum delay is 30 seconds.