Method for recovering WebSocket communication reconnection and related device

By employing a finite state machine, a dual-channel heartbeat mechanism, and a non-standard LRU strategy, the problem of automatic recovery after WebSocket connection interruption is solved, improving connection stability and message transmission success rate.

CN120979913BActive Publication Date: 2025-12-30SHENZHEN ECHOSENS MEDICAL EQUIP CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202511510195.9
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2025-10-22
Publication Date
2025-12-30
Estimated Expiration
2045-10-22

AI Technical Summary

Technical Problem

The existing WebSocket API will actively close the connection after a long period of inactivity. There is no automatic recovery mechanism after the connection is interrupted, which leads to chaotic state management.

Method used

A finite state machine is used to manage the WebSocket connection lifecycle. A non-standard LRU strategy combining a dual-channel heartbeat mechanism and timing priority is used. The reconnection interval is calculated through an exponential backoff algorithm, and unsent messages are retransmitted after the connection is restored.

Benefits of technology

It achieves automated reconnection and recovery of WebSocket connections, improves message retransmission success rate to 99.99%, reduces memory usage by 40%, and ensures timely transmission of critical messages.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120979913B_ABST
    Figure CN120979913B_ABST
Patent Text Reader

Abstract

The application provides a WebSocket communication reconnection recovery method and related equipment, which comprises the following steps: managing the life cycle of a WebSocket connection through a finite state machine; monitoring the WebSocket connection state by using a double-channel heartbeat mechanism, wherein a client is configured to send a PING frame of a current timestamp at a dynamic heartbeat interval for an uplink channel, and a server is configured to return a PONG frame of the current timestamp within a preset response time for a downlink channel; when the connection is interrupted, a non-standard LRU strategy combining time sequence priority is used to cache unsent messages, and an exponential backoff algorithm is used to calculate a reconnection interval time; finally, the WebSocket connection is reconnected based on the reconnection interval time, and the unsent messages are retransmitted through the non-standard LRU strategy after the connection is recovered. The application uses a finite state machine to manage the WebSocket, a double-channel heartbeat mechanism and an exponential backoff fast reconnection, and a non-standard LRU strategy to ensure that key information is not lost, thereby solving the defect that the original WebSocket management is chaotic and unreliable.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of communication technology, and in particular to a method and related equipment for WebSocket communication reconnection and recovery. Background Technology

[0002] With the development of real-time web communication technology, the WebSocket protocol, due to its full-duplex communication characteristics, has been widely used in scenarios such as financial market data push, IoT monitoring, and online collaboration. However, the native WebSocket API suffers from chaotic state management, with connections being actively closed by the server after prolonged inactivity, requiring manual reconnection after connection interruption, and lacking an automatic recovery mechanism.

[0003] Therefore, existing technologies still need to be improved and developed. Summary of the Invention

[0004] This invention provides a method and related equipment for WebSocket communication reconnection and recovery. The main purpose of this invention is to solve the technical problems mentioned in the background art of the prior art.

[0005] The first aspect of this invention provides a method for WebSocket communication reconnection recovery, comprising:

[0006] The lifecycle of a WebSocket connection is managed by a finite state machine, which includes five states: initialization, connecting, connected, reconnecting, and closed.

[0007] A dual-channel heartbeat mechanism is used to monitor the WebSocket connection status. For the uplink channel, the client is configured to send a PING frame carrying the current timestamp to the server at a dynamic heartbeat interval calculated by combining historical response delays. For the downlink channel, the server is configured to return a PONG frame carrying the current timestamp to the client within a preset response time.

[0008] When a connection is interrupted, unsent messages are buffered using a non-standard LRU strategy that combines timing priorities, and the reconnection interval is calculated based on an exponential backoff algorithm. The reconnection interval is defined as min(base latency × 2). n The base latency and the maximum latency are dynamically configured according to the network type.

[0009] The WebSocket connection is reconnected based on the reconnection interval, and the unsent messages are retransmitted using the non-standard LRU strategy after the connection is restored.

[0010] In an optional embodiment of the first aspect of the present invention, the step of configuring the client to send a PING frame carrying the current timestamp to the server using a dynamic heartbeat interval calculated in conjunction with historical response delays for the uplink channel includes:

[0011] Determine whether the client is sending a PING frame for the first time;

[0012] If the client is sending the PING frame for the first time, the default value is obtained as the RTT coefficient, and the dynamic heartbeat interval is obtained by multiplying the base interval time by (1 + the RTT coefficient).

[0013] If the client is not sending the PING frame for the first time, the historical response delay of the previous PING-PONG interaction is obtained, the historical response delay is divided by a preset fixed value to obtain the RTT coefficient, and the dynamic heartbeat interval is obtained by multiplying the base interval time by (1 + the RTT coefficient).

[0014] In an optional embodiment of the first aspect of the present invention, reconnecting the WebSocket connection based on the reconnection interval includes:

[0015] A WebSocket reconnection request can be initiated directly to the server based on the reconnection interval time; or a random jitter time can be obtained first through a random number generator with a preset number range, and then the random jitter time and the reconnection interval time can be added together to obtain the deduplication interval time, and then a WebSocket reconnection request can be initiated to the server based on the deduplication interval time.

[0016] In an optional embodiment of the first aspect of the present invention, the non-standard LRU strategy includes:

[0017] A hybrid structure of hash table and doubly linked list is constructed to store high-priority and low-priority unsent messages. The hash table stores the mapping between message ID and message body, and the doubly linked list is used to maintain the access order and priority of messages.

[0018] When the cache capacity of the hybrid structure exceeds the threshold, the unsent messages that are early in time and have low priority at the tail of the doubly linked list are evicted.

[0019] The high-priority unsent messages are stored separately in a persistent queue to prevent them from being evicted.

[0020] In an optional embodiment of the first aspect of the present invention, the non-standard LRU strategy further includes:

[0021] When a network quality degradation is detected, the cache capacity of the hybrid structure will be automatically increased by a preset ratio.

[0022] A time-to-live (TTL) is configured for each unsent message in the hybrid structure, and a final retransmission is triggered when the unsent message has been stored for longer than the TTL.

[0023] In an optional embodiment of the first aspect of the present invention, the verification logic of the PONG frame includes:

[0024] Listen for the pong event of the WebSocket and extract the timestamp from the returned data;

[0025] If the timestamp matches a record in the pendingPongs set, update the last valid response time.

[0026] If no matching PONG frame is received within 10 seconds, the heartbeat is deemed to have failed and a subsequent reconnection process is triggered.

[0027] In an optional embodiment of the first aspect of the present invention, the transition rules of the finite state machine include:

[0028] The transition from the connected state to the reconnecting state is triggered by a network interruption event;

[0029] If the reconnection is successful, the system returns to the connected state; otherwise, it enters the closed state after reaching the maximum number of retries.

[0030] Upon receiving a shutdown command in any state, immediately switch to the already shut-down state and release resources.

[0031] A second aspect of the present invention provides an apparatus for WebSocket communication reconnection recovery, the apparatus comprising:

[0032] The state management module is used to manage the lifecycle of a WebSocket connection through a finite state machine, which includes five states: initialization, connecting, connected, reconnecting, and closed.

[0033] The connection monitoring module is used to monitor the WebSocket connection status using a dual-channel heartbeat mechanism. For the uplink channel, the client is configured to send a PING frame carrying the current timestamp to the server at a dynamic heartbeat interval calculated by combining historical response delays. For the downlink channel, the server is configured to return a PONG frame carrying the current timestamp to the client within a preset response time.

[0034] The reconnection interval calculation module is used to buffer unsent messages using a non-standard LRU strategy combining timing priorities when the connection is interrupted, and calculates the reconnection interval time based on the exponential backoff algorithm. The reconnection interval time = min(base delay time × 2) nThe base latency and the maximum latency are dynamically configured according to the network type.

[0035] The message reconnection sending module is used to reconnect the WebSocket connection based on the reconnection interval, and resend the unsent messages through the non-standard LRU strategy after the connection is restored.

[0036] A third aspect of the present invention provides a device for WebSocket communication reconnection recovery, the device comprising: a memory and at least one processor, the memory storing instructions, and the memory and the at least one processor being interconnected via a line;

[0037] The at least one processor invokes the instructions in the memory to cause the WebSocket communication reconnection recovery device to perform the WebSocket communication reconnection recovery method as described in any one of the first aspects of the present invention.

[0038] A fourth aspect of the present invention provides a computer-readable storage medium storing a computer program that, when executed by a processor, implements the WebSocket communication reconnection recovery method as described in any one of the first aspects of the present invention.

[0039] Beneficial Effects: This invention provides a method and related equipment for WebSocket communication reconnection and recovery. The method includes managing the lifecycle of a WebSocket connection using a finite state machine; employing a dual-channel heartbeat mechanism to monitor the WebSocket connection status, configuring the client to send a PING frame with the current timestamp at a dynamic heartbeat interval for the uplink channel, and configuring the server to return a PONG frame with the current timestamp within a preset response time for the downlink channel; when the connection is interrupted, caching unsent messages using a non-standard LRU strategy combining time-series priorities and calculating the reconnection interval based on an exponential backoff algorithm; finally, reconnecting the WebSocket connection based on the reconnection interval, and retransmitting unsent messages using the non-standard LRU strategy after the connection is restored. This invention uses a finite state machine to manage WebSocket, a heartbeat mechanism and exponential backoff to quickly establish reconnection, and a non-standard LRU strategy to prevent the loss of critical information, thus solving the defects of the native WebSocket API in managing chaotic and unreliable connections. Attached Figure Description

[0040] Figure 1 This is a schematic diagram illustrating an embodiment of the main steps of a WebSocket communication reconnection and recovery method according to the present invention;

[0041] Figure 2 This is a schematic diagram of an embodiment of the WebSocket communication reconnection and recovery device of the present invention;

[0042] Figure 3 This is a schematic diagram of an embodiment of a WebSocket communication reconnection and recovery device according to the present invention. Detailed Implementation

[0043] The terms "first," "second," "third," "fourth," etc. (if present) in the specification, claims, and accompanying drawings of this invention are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments described herein can be implemented in orders other than those illustrated or described herein. Furthermore, the terms "comprising" or "having" and any variations thereof are intended to cover a non-exclusive inclusion; for example, a process, method, system, product, or apparatus that comprises a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.

[0044] For ease of understanding, the specific process of the embodiments of the present invention is described below. Please refer to [link / reference]. Figure 1 The first aspect of the present invention provides a method for WebSocket communication reconnection recovery, comprising:

[0045] S100. Manage the lifecycle of a WebSocket connection using a finite state machine, which includes five states: initialization, connecting, connected, reconnecting, and closed. A finite state machine (FSM) is a mathematical model used to describe the behavior of a system transitioning between a finite number of states according to rules. It includes the following core elements: State: The state of the system at a given moment; Event: The condition that triggers a state transition; Action: The operation performed after the event is triggered; and Transition: The rules for switching between states. A finite state machine is a powerful tool that simplifies system design and implementation by decomposing complex problems into a finite number of states and transition rules. Its clear structure improves code maintainability and scalability, making it easier to manage and debug code when facing complex logic.

[0046] The working principle of a finite state machine: State initialization: The system starts from a preset initial state (such as the "initialization" state in a WebSocket connection). Event-driven transitions: When an event occurs, a transition rule is matched according to the current state and the event type. For example, in WebSocket encapsulation: a network interruption event triggers a transition from "connected" to "reconnecting". Action execution: State transitions may be accompanied by actions, such as sending a heartbeat packet (WebSocket's PING action) with current attachment information, or performing message retransmission (LRU queue buffering) with current attachment information. Termination condition: Reaching a termination state (such as "closed" in WebSocket) or satisfying the maximum number of retries. Specifically, in an optional embodiment of the first aspect of the present invention, the transition rules of the finite state machine may include: triggering a transition from the connected state to the reconnecting state through a network interruption event; returning to the connected state after successful reconnection, otherwise entering the closed state after reaching the maximum number of retries; and immediately jumping to the closed state and releasing resources upon receiving a close command in any state.

[0047] S200: A dual-channel heartbeat mechanism is used to monitor the WebSocket connection status. For the uplink channel, the client is configured to send a PING frame carrying the current timestamp to the server at a dynamic heartbeat interval calculated based on historical response delays. For the downlink channel, the server is configured to return a PONG frame carrying the current timestamp to the client within a preset response time. In this invention, a dynamic heartbeat mechanism is used (to solve the idle timeout problem). Uplink PING frame: actively sent by the client (including timestamp). Downlink PONG frame: the server must return a matching timestamp within a preset response time (e.g., 10s). Furthermore, by dynamically adjusting the heartbeat interval (formula: base interval time × [1 + RTT coefficient], the base interval time can be, for example, 30s, the default RTT coefficient is 0.5 for the first time, and the RTT coefficient for subsequent timestamps can be dynamically calculated using historical response times, for example, by using the historical response delay of the last PING-PONG interaction / a preset fixed value (e.g., 2000)), network adaptation is achieved, significantly improving connection stability.

[0048] In an optional embodiment of the first aspect of the present invention, the step of configuring the client to send a PING frame carrying the current timestamp to the server with a dynamic heartbeat interval calculated in conjunction with historical response delays for the uplink channel includes: determining whether the client is sending the PING frame for the first time; if the client is sending the PING frame for the first time, obtaining a default value as the RTT coefficient, and obtaining the dynamic heartbeat interval by multiplying the base interval time by (1 + the RTT coefficient); if the client is not sending the PING frame for the first time, obtaining the historical response delay of the previous PING-PONG interaction (the total round-trip time from the user to the server and back from the server to the user in the previous heartbeat data packet), dividing the historical response delay by a preset fixed value to obtain the RTT coefficient, and obtaining the dynamic heartbeat interval by multiplying the base interval time by (1 + the RTT coefficient). In an optional embodiment of the first aspect of the present invention, the verification logic of the PONG frame includes: listening to the pong event of the WebSocket and extracting the timestamp from the returned data; if the timestamp matches the record in the pendingPongs set, updating the last valid response time; if no matching PONG frame is received for more than 10 seconds, determining that the heartbeat has failed and triggering the subsequent reconnection process.

[0049] In this invention, frame type identification can be distinguished using the WebSocket protocol standard opcode: for example, 0x9: PING frame (sent by the client); 0xA: PONG frame (responded by the server). Data association verification uses a timestamp matching mechanism. PONG response verification also includes data consistency checks. The state synchronization strategy resets lastActivityTime for each valid communication (including business messages). Heartbeat detection is based on time difference calculation. In general, the heartbeat detection of this invention adopts a dual protection mechanism, combining active probing (uplink PING) with passive monitoring (downlink timeout). When there is network jitter, business messages are used to replace heartbeats first (reducing redundant traffic). The dynamic adaptive dynamic heartbeat interval = basic interval time × (1 + RTT coefficient). The RTT coefficient is dynamically calculated through historical response time (default 0.5). Furthermore, this invention can also incorporate fault tolerance design, such as allowing three consecutive heartbeat failures before determining a connection abnormality.

[0050] S300: When the connection is interrupted, unsent messages are buffered using a non-standard LRU strategy combining time-series priority, and the reconnection interval is calculated based on the exponential backoff algorithm. The reconnection interval = min(base delay time × 2). nThe base latency and the maximum latency are dynamically configured based on the network type. Traditional LRU (Least Recently Used) is a cache eviction algorithm based on access time. Its core principle is: when cache space is insufficient, the least recently used data is evicted first.

[0051] The data structures of the traditional LRU strategy include: a hash table (Map): storing the mapping between message IDs and message bodies (O(1) time complexity for querying); a doubly linked list: maintaining the access order of messages, with the most recently accessed message at the head of the list and the least recently accessed message at the tail. When a new message arrives, it is stored in both the Map and the head of the list. When the cache is full, the message at the tail of the list is automatically removed.

[0052] This invention improves upon the traditional LRU by incorporating message priority. Business messages can be marked with priorities (such as price update messages in financial market data). High-priority messages are not evicted by LRU and are stored separately in a persistent queue. The specific differences between this invention's non-standard LRU strategy and the traditional LRU are shown in Table 1 below:

[0053] Table 1. Differences between the non-standard LRU strategy of this invention and the traditional LRU strategy

[0054]

[0055] Based on the above description, in an optional embodiment of the first aspect of the present invention, the non-standard LRU strategy includes: constructing a hybrid structure of a hash table and a doubly linked list to store high-priority and low-priority unsent messages, wherein the hash table stores the mapping between message IDs and message bodies, and the doubly linked list is used to maintain the access sequence and priority of messages; when the cache capacity of the hybrid structure exceeds a threshold, the unsent messages with earlier timing and lower priority at the tail of the doubly linked list are evicted; and the high-priority unsent messages are stored independently in a persistent queue to avoid being evicted.

[0056] In this invention, the exponential backoff algorithm used for connection reconnection intervals is a strategy for dynamically adjusting retry intervals. It handles network conflicts or service unavailability scenarios by exponentially increasing the waiting time. Based on the multi-level reconnection mechanism of the exponential backoff algorithm, and combined with the network type (4G / 5G / WiFi), it automatically selects the optimal reconnection strategy. Its core formula is: delay = min(BASE_DELAY × 2). n`BASE_DELAY`: Base latency (e.g., 1 second), `n`: Current retry count, `MAX_DELAY`: Maximum latency (e.g., 30 seconds). The base latency and maximum latency can be set differently for different network types. Guided by the exponential backoff algorithm, a retry will occur immediately after the first failed reconnection. Subsequent failures will double the interval until the maximum number of retries (e.g., 5) is reached, at which point the operation is abandoned. Calculating the reconnection interval based on the exponential backoff algorithm enables dynamic load adaptation: for minor faults, short intervals allow for rapid recovery (e.g., successful retry after 1 second); for severe faults, long intervals prevent avalanche effects (e.g., a 30-second interval reduces invalid requests); and it optimizes resources, saving client resources by reducing CPU / network usage (compared to fixed-interval retries), and protecting the server by providing a recovery buffer for the server through exponentially increasing intervals. The advantages of exponential backoff compared to fixed-interval strategies can be seen in Table 2.

[0057] Table 2. Performance Comparison Table of Indexed Retreat and Fixed Interval Indicators

[0058]

[0059] S400. Reconnect the WebSocket connection based on the reconnection interval, and resend the unsent messages using the non-standard LRU strategy after the connection is restored. In an optional embodiment of the first aspect of the present invention, reconnecting the WebSocket connection based on the reconnection interval includes: directly initiating a WebSocket reconnection request to the server based on the reconnection interval.

[0060] Alternatively, a random jitter time can be obtained first using a random number generator with a preset range of generated numbers. Then, the random jitter time and the reconnection interval time are added together to obtain the deduplication interval time. Finally, a WebSocket reconnection request is initiated to the server based on the deduplication interval time. In this implementation, to avoid simultaneous retries by multiple clients, random jitter is introduced by adding a random value (e.g., ±0.5 seconds) to the calculation interval, discretizing the retry time and reducing the probability of secondary collisions.

[0061] In this invention, a fault tolerance mechanism can be further configured in the non-standard LRU strategy. In an optional embodiment of the first aspect of this invention, the non-standard LRU strategy further includes: when a network quality degradation is detected, automatically expanding the cache capacity of the hybrid structure by a preset ratio (e.g., 20-50%); and configuring a time-to-live (TTL) limit for each unsent message in the hybrid structure, triggering a final retransmission when the unsent message exceeds the TTL. That is, in this invention, the cache hit ratio can be calculated in real time, the cache capacity can be dynamically adjusted (e.g., fluctuating between 50-100 messages based on the overall network quality), and a message time-to-live (TTL) limit can be configured (default 5 minutes), triggering a final retry before eviction.

[0062] Overall, the main optimization mechanisms of the WebSocket communication reconnection recovery method of this invention are as follows: Unified state control: The connection lifecycle (initialization, connecting, connected, reconnecting, closed) is managed through a finite state machine to ensure the consistency of state transition logic. Dynamic heartbeat mechanism: Through dual-channel PING-PONG interaction (uplink sending timestamped PING frames, downlink verifying PONG frames within 10 seconds), combined with the formula dynamic heartbeat interval = base interval time × (1 + RTT coefficient), the heartbeat frequency is dynamically adjusted to reduce redundant traffic by 30%-70%. Intelligent reconnection strategy: An exponential backoff algorithm is adopted (reconnection interval time = min(base delay time × 2)). n Maximum latency) and can be combined with random jitter (±0.5s), and the parameters can be dynamically configured according to the network type (4G / 5G / WiFi) to achieve fast connection recovery within 5 seconds; Hybrid message queue management: based on the LRU strategy (hash table + doubly linked list) to cache unsent messages, with a default capacity of 50 messages, combined with priority queues to ensure zero loss of critical messages.

[0063] The WebSocket communication reconnection recovery method of this invention improves the message retransmission success rate to 99.99% (compared to 95% for the FIFO strategy), reduces memory usage by 40% (through intelligent elimination of invalid messages), prioritizes the transmission of the latest price data for high-frequency market data pushes, and ensures that control commands are not blocked by outdated data for IoT commands.

[0064] See Figure 2 A second aspect of the present invention provides an apparatus for WebSocket communication reconnection recovery, the apparatus comprising:

[0065] State management module 10 is used to manage the lifecycle of a WebSocket connection through a finite state machine, which includes five states: initialization, connecting, connected, reconnecting, and closed.

[0066] The connection monitoring module 20 is used to monitor the WebSocket connection status using a dual-channel heartbeat mechanism. For the uplink channel, the client is configured to send a PING frame carrying the current timestamp to the server at a dynamic heartbeat interval calculated by combining historical response delays. For the downlink channel, the server is configured to return a PONG frame carrying the current timestamp to the client within a preset response time.

[0067] The reconnection interval calculation module 30 is used to cache unsent messages using a non-standard LRU strategy combining timing priorities when the connection is interrupted, and calculate the reconnection interval time based on the exponential backoff algorithm. The reconnection interval time = min(base delay time × 2) n The base latency and the maximum latency are dynamically configured according to the network type.

[0068] The message reconnection sending module 40 is used to reconnect the WebSocket connection based on the reconnection interval time, and resend the unsent messages through the non-standard LRU strategy after the connection is restored.

[0069] In an optional embodiment of the second aspect of the present invention, the connection monitoring module includes:

[0070] The initial determination unit is used to determine whether the client is sending a PING frame for the first time;

[0071] The first heartbeat interval calculation unit is used to obtain a default value as the RTT coefficient if the client is sending the PING frame for the first time, and obtain the dynamic heartbeat interval by multiplying the base interval time by (1 + the RTT coefficient).

[0072] The second heartbeat interval calculation unit is used to obtain the historical response delay of the previous PING-PONG interaction if the client is not sending the PING frame for the first time, divide the historical response delay by a preset fixed value to obtain the RTT coefficient, and obtain the dynamic heartbeat interval by the base interval time × (1 + the RTT coefficient).

[0073] In an optional embodiment of the second aspect of the present invention, the message reconnection sending module includes:

[0074] The direct reconnection unit is used to directly initiate a WebSocket reconnection request to the server based on the reconnection interval time.

[0075] The deduplication and reconnection unit is used to first obtain the random jitter time through a random number generator with a preset number range, then add the random jitter time and the reconnection interval time to obtain the deduplication interval time, and then initiate a WebSocket reconnection request to the server based on the deduplication interval time.

[0076] In an optional embodiment of the second aspect of the present invention, the non-standard LRU strategy includes:

[0077] A hybrid structure of hash table and doubly linked list is constructed to store high-priority and low-priority unsent messages. The hash table stores the mapping between message ID and message body, and the doubly linked list is used to maintain the access order and priority of messages.

[0078] When the cache capacity of the hybrid structure exceeds the threshold, the unsent messages that are early in time and have low priority at the tail of the doubly linked list are evicted.

[0079] The high-priority unsent messages are stored separately in a persistent queue to prevent them from being evicted.

[0080] In an optional embodiment of the second aspect of the present invention, the non-standard LRU strategy further includes:

[0081] When a network quality degradation is detected, the cache capacity of the hybrid structure will be automatically increased by a preset ratio.

[0082] A time-to-live (TTL) is configured for each unsent message in the hybrid structure, and a final retransmission is triggered when the unsent message has been stored for longer than the TTL.

[0083] In an optional embodiment of the second aspect of the present invention, the verification logic of the PONG frame includes:

[0084] Listen for the pong event of the WebSocket and extract the timestamp from the returned data;

[0085] If the timestamp matches a record in the pendingPongs set, update the last valid response time.

[0086] If no matching PONG frame is received within 10 seconds, the heartbeat is deemed to have failed and a subsequent reconnection process is triggered.

[0087] In an optional embodiment of the second aspect of the present invention, the transition rules of the finite state machine include:

[0088] The transition from the connected state to the reconnecting state is triggered by a network interruption event;

[0089] If the reconnection is successful, the system returns to the connected state; otherwise, it enters the closed state after reaching the maximum number of retries.

[0090] Upon receiving a shutdown command in any state, immediately switch to the already shut-down state and release resources.

[0091] Figure 3 This is a schematic diagram of a WebSocket communication reconnection and recovery device according to an embodiment of the present invention. This device can vary significantly due to different configurations or performance characteristics, and may include one or more processors 50 (central processing units, CPUs) (e.g., one or more processors) and memory 60, and one or more storage media 70 (e.g., one or more mass storage devices) for storing applications or data. The memory and storage media can be temporary or persistent storage. The program stored in the storage media may include one or more modules (not shown in the diagram), each module including a series of instruction operations on the WebSocket communication reconnection and recovery device. Furthermore, the processor may be configured to communicate with the storage media and execute the series of instruction operations stored in the storage media on the WebSocket communication reconnection and recovery device.

[0092] The WebSocket communication reconnection and recovery device of this invention may further include one or more power supplies 80, one or more wired or wireless network interfaces 90, one or more input / output interfaces 100, and / or one or more operating systems, such as Windows Server, Mac OS X, Unix, Linux, FreeBSD, etc. Those skilled in the art will understand that... Figure 3 The device structure shown for WebSocket communication reconnection recovery does not constitute a limitation on the device for WebSocket communication reconnection recovery, and may include more or fewer components than shown, or combine certain components, or have different component arrangements.

[0093] The present invention also provides a computer-readable storage medium, which may be a non-volatile computer-readable storage medium or a volatile computer-readable storage medium, wherein the computer-readable storage medium stores instructions that, when the instructions are executed on a computer, cause the computer to perform the steps of the WebSocket communication reconnection recovery method.

[0094] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the specific working process of the system or system / unit described above can be referred to the corresponding process in the foregoing method embodiments, and will not be repeated here.

[0095] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of the present invention, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of the present invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.

[0096] The above-described embodiments are only used to illustrate the technical solutions of the present invention, and are not intended to limit it. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention.

Claims

1. A method for WebSocket communication reconnection recovery, characterized in that, The application relates to a WebSocket connection management method and system. The WebSocket connection life cycle is managed by a finite state machine, which includes five states of initialization, connection, connection, reconnection and closure; A double-channel heartbeat mechanism is used to monitor the WebSocket connection state, wherein a client is configured to send a PING frame carrying a current timestamp to a server at a dynamic heartbeat interval calculated by combining a historical response delay for an uplink channel, and the server is configured to return a PONG frame carrying the current timestamp to the client within a preset response time for a downlink channel; When the connection is interrupted, the non-standard LRU strategy combined with the timing priority caches the unsent message, and calculates the reconnection interval time based on the exponential backoff algorithm, the reconnection interval time = min (base delay time x 2 n , maximum delay time), wherein n is the current reconnection number, and the base delay time and the maximum delay time are dynamically configured according to the network type; The WebSocket connection is reconnected based on the reconnection interval time, and the unsent messages are retransmitted by the non-standard LRU strategy after the connection is restored.

2. The method for WebSocket communication reconnection recovery according to claim 1, wherein, The method comprises the following steps: determining whether the client is sending the PING frame for the first time; if the client is sending the PING frame for the first time, a default value is obtained as an RTT coefficient, and the dynamic heartbeat interval is obtained by multiplying the basic interval time by (1+the RTT coefficient); if the client is not sending the PING frame for the first time, a historical response delay of the last PING-PONG interaction is obtained, the historical response delay is divided by a preset fixed value to obtain the RTT coefficient, and the dynamic heartbeat interval is obtained by multiplying the basic interval time by (1+the RTT coefficient).

3. The method for WebSocket communication reconnection recovery according to claim 1, wherein, The WebSocket connection is reconnected based on the reconnection interval time, and the unsent messages are retransmitted by the non-standard LRU strategy after the connection is restored. The non-standard LRU strategy comprises the following steps:

4. The method for WebSocket communication reconnection recovery according to claim 1, wherein, a hybrid structure of a hash table and a double-directional list is constructed to store unsent messages with high and low priorities, wherein the hash table stores the mapping between message IDs and message bodies, and the double-directional list is used to maintain the access time sequence and priority of the messages; when the cache capacity of the hybrid structure exceeds a threshold value, the unsent messages with low priorities and early time sequence at the tail of the double-directional list are eliminated; the unsent messages with high priorities are independently stored in a persistent queue to avoid elimination. The non-standard LRU strategy further comprises the following steps:

5. The method of WebSocket communication reconnection recovery according to claim 4, characterized in that, when the network quality is monitored to decrease, the cache capacity of the hybrid structure is automatically expanded by a preset proportion; and a survival time is configured for each unsent message in the hybrid structure, and the last retransmission is triggered when the unsent message is stored for more than the survival time. The verification logic of the PONG frame comprises the following steps:

6. The method for WebSocket communication reconnection recovery according to claim 1, wherein, listening to the pong event of the WebSocket, and extracting the timestamp in the returned data; if the timestamp matches the record in the pendingPongs set, updating the last valid response time; ​ If no matching PONG frame is received within 10 seconds, the heartbeat is determined to fail and a subsequent reconnection process is triggered.

7. The method for WebSocket communication reconnection recovery according to claim 1, wherein, The transition rules of the finite state machine include: The transition from the connected state to the reconnection state is triggered by a network interruption event; The connected state is returned after a successful reconnection, otherwise the closed state is entered after a maximum number of retries is reached; In any state, receiving a close instruction immediately jumps to the closed state and releases resources.

8. A device for WebSocket communication reconnection recovery, characterized in that, The WebSocket communication reconnection recovery device includes: A state management module for managing the life cycle of a WebSocket connection through a finite state machine, the finite state machine including five states: initialization, connection, connected, reconnection, and closed; A connection monitoring module for monitoring the WebSocket connection state using a dual-channel heartbeat mechanism, for the uplink channel, configuring a client to send a PING frame carrying a current timestamp to a server with a dynamic heartbeat interval calculated based on historical response delays, and for the downlink channel, configuring the server to return a PONG frame carrying the current timestamp to the client within a preset response time; The reconnection interval calculation module is configured to cache the unsent messages by the non-standard LRU strategy combining the time sequence priority when the connection is interrupted, and calculate the reconnection interval time based on the exponential backoff algorithm, wherein the reconnection interval time = min (base delay time x 2 n , maximum delay time), wherein n is the current reconnection number, and the base delay time and the maximum delay time are dynamically configured according to the network type. The reconnection interval calculation module is configured to cache the unsent messages by the non-standard LRU strategy combining the time sequence priority when the connection is interrupted, and calculate the reconnection interval time based on the exponential backoff algorithm, wherein the reconnection interval time = min (base delay time x 2 n , maximum delay time), wherein n is the current reconnection number, and the base delay time and the maximum delay time are dynamically configured according to the network type. A message reconnection sending module for reconnecting the WebSocket connection based on the reconnection interval time and retransmitting the unsent messages after connection recovery using the non-standard LRU strategy.

9. A device for WebSocket communication reconnection recovery, characterized by, The WebSocket communication reconnection recovery device includes a memory and at least one processor, the memory having instructions stored therein, the memory and the at least one processor being interconnected by a circuit; The at least one processor invokes the instructions in the memory to cause the WebSocket communication reconnection recovery device to perform the WebSocket communication reconnection recovery method of any one of claims 1-7.

10. A computer-readable storage medium having stored thereon a computer program, characterized in that, The computer program, when executed by a processor, implements the WebSocket communication reconnection recovery method of any one of claims 1-7.

Citation Information

Patent Citations

  • Communication connection management method and system

    CN118827746A

  • Base station communication method and system based on Websocket protocol, electronic device and storage medium

    CN120416313A