A session management method and system based on KCP protocol

By using the hash table and multi-threaded collaborative optimization system of the KCP protocol, the problems of low session management efficiency and resource contention in high-concurrency scenarios of the KCP protocol are solved, achieving efficient session management and data transmission, and improving the system's processing capacity and stability.

CN120856756BActive Publication Date: 2025-12-05JIANGSU YUANXIN WANGAN TECH CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

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

AI Technical Summary

Technical Problem

The existing KCP protocol lacks an efficient session identification and differentiation mechanism in high-concurrency scenarios, which makes it difficult to manage multiple concurrent sessions, makes it difficult to ensure fairness in resource-sharing environments, lacks a unified state synchronization and maintenance mechanism for session establishment, maintenance and teardown, leads to unreasonable thread scheduling resulting in wasted CPU resources, and has insufficient flexibility in input/output interfaces, making it unable to adapt to diverse platform requirements.

Method used

A session management method based on the KCP protocol is adopted, which realizes session lookup with O(1) time complexity through hash table. Combined with multi-threaded collaborative optimization system, including KCP update thread, idle detection thread and event polling receiving thread, with bucket locking mechanism and atomic operation, it supports input and output in UDP mode and user-defined mode, and optimizes the send and receive window size.

Benefits of technology

It improves session management efficiency, solves resource contention issues in high-concurrency scenarios, enhances system processing capabilities and stability, adapts to different platforms and non-network transmission scenarios, and provides highly reliable, high-concurrency, and low-latency data transmission services.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120856756B_ABST
    Figure CN120856756B_ABST
Patent Text Reader

Abstract

The application provides a KCP protocol-based session management method and system. The method constructs a KCP context containing a session hash table and an active session linked list through a session management system initialization step, cooperates with the multi-thread cooperative work of a KCP update thread, an idle detection thread and an event polling receiving thread, realizes the efficient creation, search, data sending and receiving and release process of the session, effectively solves the low efficiency of session management and resource competition problem in the high concurrency scene of the traditional KCP application, and significantly improves the system processing capacity and stability.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The present application relates to the field of data transmission, in particular to a KCP protocol-based session management method and system. BACKGROUND

[0002] In modern Internet applications, session management, as a key technology for human-computer interaction, undertakes the core responsibility of maintaining user operation coherence and system security. Among them, the selection of network transmission protocol directly affects the performance and user experience of the application. Although the Transmission Control Protocol (TCP) provides reliable transmission services, its congestion control and retransmission mechanism leads to high delay, which is not suitable for application scenarios with extremely high real-time requirements. Although the User Datagram Protocol (UDP) provides low-delay transmission, it lacks reliability guarantee and cannot meet the key data transmission requirements. In the fields of games, video communication, real-time collaboration and other delay-sensitive fields, traditional transmission protocols are difficult to meet the dual demands of reliability and low delay.

[0003] To solve this contradiction, an open-source fast and reliable protocol (KCP) emerges as the times require. As a reliable transmission protocol based on UDP, KCP draws on the reliable transmission mechanism of TCP, but through simplification and optimization, it realizes lower delay and higher transmission efficiency. KCP adopts selective retransmission, fast recovery and other mechanisms to ensure data reliability while significantly reducing transmission delay, especially suitable for real-time interactive applications. The emergence of KCP provides underlying transmission guarantee for building high-performance and low-delay session management, making it possible to achieve smooth user experience in complex network environments.

[0004] Therefore, the present application provides a KCP protocol-based session management method and system to solve one of the above technical problems. SUMMARY

[0005] The present application aims to provide a KCP protocol-based session management method and system that can solve at least one of the technical problems mentioned above. The specific scheme is as follows:

[0006] According to the specific embodiment of the present application, in the first aspect, the present application provides a KCP protocol-based session management method, comprising:

[0007] The session management system initializes steps, including creating and initializing a KCP context, the KCP context including a session hash table, an active session linked list, a thread control flag and an input / output mode flag; a session creation step, including creating a KCP session based on a received data packet, and assigning a session identifier to the KCP session, and storing the mapping relationship between the session identifier and the KCP session in the session hash table; a session lookup step, including looking up in the session hash table according to the session identifier to obtain the corresponding KCP session; a data sending step, including sending data through the KCP session, calling a KCP protocol interface to encapsulate the data to be sent and issuing it through an output interface; a data receiving step, including receiving data through the KCP session, calling a KCP protocol interface to parse the received data packet and extract the payload; a session release step, including releasing a KCP session that is no longer used, and removing it from the session hash table and the active session linked list; wherein the session management system runs at least three threads: a KCP update thread, for periodically updating the status of all active KCP sessions; an idle detection thread, for detecting and recycling KCP sessions that have been inactive for too long; an event polling receiving thread, for listening to input / output events and triggering data receiving processing; wherein the session management system is implemented based on the KCP protocol, including implementing the message encapsulation sending and receiving decapsulation process based on the ikcp framework, and optimizing the architecture, supporting configuration of the sending / receiving window size, and expanding the upper limit of single sending data from KB level to MB level; wherein the session hash table uses a bucket locking mechanism, each hash bucket is equipped with an independent mutex, and when performing add, delete, modify and query operations, only the hash bucket corresponding to the add, delete, modify and query operation is locked.

[0008] In an embodiment, the session hash table is used to store KCP session pointers with session identifiers as keys, realizing session lookup with O(1) time complexity.

[0009] In an embodiment, the KCP update thread traverses the session hash table at a fixed time interval, and calls a KCP update function to update each session; the idle detection thread periodically checks the last active time of the session, and if it is timed out, triggers session release; the event polling receiving thread listens to socket events based on an event polling mechanism, and when data is received, calls a KCP data input function for processing.

[0010] In an embodiment, the KCP update thread uses a nanosecond-level sleep function for time control.

[0011] In an embodiment, the change of session status is realized through atomic operation, including updating the session validity flag and the last active time.

[0012] In one embodiment, the input / output mode flag supports at least one of a UDP mode and a user-defined mode; wherein, for the UDP mode, a socket interface is used for data transmission and reception; and for the user-defined mode, a user-provided input / output function is used for data transmission and reception.

[0013] In one embodiment, for the user-defined mode, the input / output function is configured to adapt to a non-network transmission scenario, and perform data transmission across platforms or a custom protocol.

[0014] In one embodiment, the active session linked list is a double-linked list structure, supports a first-in-first-out queue management, is used to cache recent active sessions, and supports session pop-out operations in non-blocking, blocking and timeout modes.

[0015] According to the specific embodiments of the present application, in a second aspect, the present application provides a KCP protocol-based session management system, comprising:

[0016] A session management module for implementing the KCP protocol-based session management method of the first aspect; the session management module comprises: a session hash table unit for storing the mapping relationship between the session identifier and the session object; an active session linked list unit for maintaining recent active sessions; a multi-thread scheduling unit for managing the creation and cooperation of the KCP update thread, the idle detection thread and the event polling reception thread; and an input / output adaptation unit for selecting a data transmission and reception mode according to a flag bit; wherein, the system is configured to run on a server or a client device supporting the KCP protocol; wherein, the session hash table adopts a bucket locking mechanism, each hash bucket is equipped with an independent mutex, and only the hash bucket corresponding to the add, delete, modify and query operation is locked when the add, delete, modify and query operation is performed.

[0017] Compared with the prior art, the above-mentioned scheme of the embodiments of the present application has at least the following beneficial effects:

[0018] The present application provides a KCP protocol-based session management method and system. The method initializes the KCP context containing the session hash table and the active session linked list through the session management system initialization step, cooperates the multi-thread cooperative work of the KCP update thread, the idle detection thread and the event polling reception thread, realizes the efficient creation, lookup, data sending and receiving and release process of the session, effectively solves the low efficiency of session management and resource competition problem in the high concurrency scene of the traditional KCP application, and significantly improves the system processing capacity and stability. BRIEF DESCRIPTION OF DRAWINGS

[0019] Figure 1 A flowchart of a KCP protocol-based session management method is shown;

[0020] Figure 2A session creation flowchart is shown;

[0021] Figure 3 A session search flowchart is shown;

[0022] Figure 4 A session data sending flowchart is shown;

[0023] Figure 5 A session data receiving flowchart is shown;

[0024] Figure 6 A session release flowchart is shown;

[0025] Figure 7 A hash table management flowchart is shown;

[0026] Figure 8 A live session management flowchart is shown;

[0027] Figure 9 A KCP update thread diagram is shown;

[0028] Figure 10 A KCP idle session detection flowchart is shown;

[0029] Figure 11 An epoll receiving thread flowchart is shown;

[0030] Figure 12 An input / output extended interface operation thread diagram is shown;

[0031] Figure 13 A unit block diagram of a KCP protocol-based session management system according to an embodiment of the present application is shown;

[0032] Figure 14 A KCP protocol-based session management system creation flowchart is shown;

[0033] Figure 15 A KCP protocol-based session management system release flowchart is shown;

[0034] Figure 16 A KCP protocol-based session management method and system overall flowchart is shown;

[0035] Figure 17 A KCP protocol-based session management method and system use flowchart example is shown. DETAILED DESCRIPTION

[0036] In order to make the objects, technical solutions and advantages of the present application clearer, the following further describes the present application in detail with reference to the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of the present application, and not all embodiments of the present application. Based on the embodiments of the present application, all other embodiments obtained by those skilled in the art without creative work fall within the scope of protection of the present application.

[0037] The terms used in the embodiments of the present application are only for the purpose of describing particular embodiments and are not intended to limit the present application. The singular forms "a", "said" and "the" used in the embodiments of the present application and the appended claims are also intended to include the plural forms, unless the context clearly indicates otherwise. "Plural" generally includes at least two.

[0038] It should be understood that the term "and / or" used herein only describes the association relationship of the associated objects, which means that there can be three relationships, for example, A and / or B, which means that there are three cases of A alone, A and B together, and B alone. In addition, the character " / " herein generally represents an "or" relationship between the front and rear associated objects.

[0039] It should be understood that although the terms first, second, third, etc. can be used in the embodiments of the present application, these descriptions should not be limited to these terms. These terms are only used to distinguish the description. For example, without departing from the scope of the embodiments of the present application, the first can also be called the second, and similarly, the second can also be called the first.

[0040] Depending on the context, the word "if" as used herein can be interpreted as "when" or "upon" or "in response to determining" or "in response to detecting". Similarly, depending on the context, the phrase "if it is determined" or "if (a stated condition or event) is detected" can be interpreted as "when it is determined" or "in response to determining" or "when (a stated condition or event) is detected" or "in response to detecting (a stated condition or event)".

[0041] It should also be noted that the terms "comprising", "including", or any other variant thereof are intended to cover non-exclusive inclusion, so that a product or system including a series of elements not only includes those elements, but also includes other elements not explicitly listed, or further includes elements inherent to such product or system. Without more limitations, the element defined by the phrase "including a" does not exclude the presence of additional identical elements in the product or system including the element.

[0042] It should be particularly noted that the symbols and / or numbers present in the specification, if not marked in the description, are not figure marks.

[0043] It should be noted that the technical terms that may be involved in the following embodiments are shown as follows, and if there is any ambiguity in the following technical terms, please refer directly to the English-Chinese interpretation shown here: Open-source fast and reliable protocol (KCP); Transmission Control Protocol (TCP); User Datagram Protocol (UDP); Input / Output Event (I / O Event); KCP update (ikcp_update) function; Socket event; KCP input (kcp_input) function; Nanosecond-level sleep (nanosleep) function; First-In, First-Out Queue (FIFO) queue; Automatic Repeat Request (ARQ); Conversation Identifier (conv); Polling / event polling (epoll); Mutual Exclusion Lock (mutex); Atomic operation; Hash table; Linked list; Timeout; Maximum Transmission Unit (MTU); Server; Client.

[0044] Currently, although the KCP protocol is a transmission protocol based on automatic repeat request (ARQ) with the advantages of low delay and high reliability, it still has significant problems in actual application, especially in high concurrency scenarios. First, KCP itself does not maintain the connection state, lacks an efficient conversation identification and differentiation mechanism, making it difficult to manage multiple conversations concurrently. Second, it is difficult to ensure fairness in a resource-sharing environment, and the performance decreases sharply as the number of conversations increases. In addition, the establishment, maintenance, and removal of conversations lack a unified state synchronization and maintenance mechanism, relying on developers to implement connection state management and parameter tuning, which not only increases the implementation complexity, but also easily causes resource leaks. At the same time, the existing scheme has unreasonable thread scheduling, causing waste of CPU resources, and the input / output interface lacks flexibility, which cannot adapt to the diversified platform requirements, further limiting its application effect and reliability.

[0045] In view of this, the application provides a KCP protocol-based session management method and system, aiming to solve the core problem of the prior art in a high concurrency scenario through a KCP protocol-based session management and multi-thread cooperative optimization system.

[0046] The optional embodiments of the application will be described in detail below with reference to the drawings.

[0047] The embodiments provided by the application, i.e., an embodiment of a KCP protocol-based session management method.

[0048] The embodiments of the application will be described in detail below with reference to the drawings. Figure 1 The embodiments of the application will be described in detail below with reference to the drawings.

[0049] Figure 1 A flowchart of a KCP protocol-based session management method is shown, as shown in Figure 1 The flowchart includes the following steps.

[0050] S101, a session management system initialization step, including creating and initializing a KCP context.

[0051] The KCP context includes a session hash table, an active session linked list, a thread control flag, and an input / output mode flag.

[0052] S102, a session creation step, including creating a KCP session based on a received data packet, and assigning a session identifier to the KCP session, and storing the mapping relationship between the session identifier and the KCP session in the session hash table.

[0053] S103, a session search step, including searching in the session hash table according to the session identifier to obtain the corresponding KCP session.

[0054] S104, a data sending step, including sending data through the KCP session, and calling a KCP protocol interface to encapsulate the data to be sent and send it out through an output interface.

[0055] S105, a data receiving step, including receiving data through the KCP session, and calling a KCP protocol interface to parse the received data packet and extract the payload.

[0056] S106, a session release step, including releasing a KCP session that is no longer used, and removing it from the session hash table and the active session linked list.

[0057] The session management system runs at least three threads: a KCP update thread for periodically updating the status of all active KCP sessions, an idle detection thread for detecting and recycling KCP sessions that have been inactive for too long, and an event polling reception thread for listening to input / output events and triggering data reception processing.

[0058] The session hash table adopts a bucket locking mechanism, each hash bucket is equipped with an independent mutex, and only the hash bucket corresponding to the adding, deleting, modifying or inquiring operation is locked when the adding, deleting, modifying or inquiring operation is performed.

[0059] The session management system is implemented based on a KCP protocol, including: implementing a message encapsulation sending and receiving decapsulation process based on an ikcp framework, optimizing the architecture, supporting configuration of a transceiving window size, and expanding the upper limit of single-time sending data from KB level to MB level.

[0060] In the embodiment of the application, first, a session management mechanism based on a hash table is introduced to realize fast mapping of a session identifier and O(1) time complexity session searching, which significantly improves the efficiency of multi-session concurrent management, and second, a multi-thread separation concern architecture is adopted, in which a dedicated thread is responsible for KCP state updating, idle session detection and I / O event listening, so as to optimize thread scheduling and reduce waste of CPU resources. At the same time, atomic operation is used to guarantee thread safety of session state change, avoid resource competition and state synchronization problems, and a flexible IO adaptation mechanism is designed to support UDP mode and user-defined input and output functions, enhancing the adaptability of the system to cross-platform and non-network scenarios. The method provided by the application fundamentally overcomes the defects of interface rigidity and resource leakage, and finally provides high-reliability, high-concurrency and low-latency data transmission services on the UDP network.

[0061] In some embodiments, the session management system initialization step includes creating and initializing a KCP context, the KCP context including a session hash table, an active session linked list, a thread control flag and an input and output mode flag. The session hash table adopts a hash table structure to manage KCP sessions, and realizes O(1) time complexity fast session searching through a session identifier. The active session linked list adopts a double-linked list structure to support first-in-first-out queue management and is used to cache recent active sessions. The thread control flag is used to control the running state of each thread. The input and output mode flag is used to specify the data transmission mode, supporting UDP mode and user-defined mode.

[0062] As a feasible embodiment, the session creation step includes creating a KCP session based on the received data packet, assigning a session identifier to the KCP session, and storing the mapping relationship between the session identifier and the KCP session in the session hash table. The session identifier is obtained through a system generation method and is used to uniquely identify each KCP session. In actual application, session creation usually occurs when the first data packet is received, and the system automatically assigns an identifier to the session corresponding to the data packet and initializes the session state.

[0063] Figure 2 A session creation flowchart is shown.

[0064] As Figure 2As shown, in the session creation process, first check whether the session transceiver descriptor is the main listening descriptor, if not, add it to the epoll listening. Then, the system allocates appropriate memory space for session management, and initializes the KCP control block for KCP protocol scheduling. Then, set the KCP output function to kcp_output, which supports UDP sending and user-defined function sending, and initialize other KCP fields, including session identifier, last active time, etc., while setting the session state to valid, ensuring thread safety. Next, set the KCP window size according to the window size of the KCP context, and configure ikcp_nodelay and stream mode according to the session management system flag. Then, adjust the KCP MTU according to the communication environment, and add the newly created session to the hash table for subsequent lookup, management and timeout release. If the active session linked list is enabled, the session will be added to the active session linked list after the KCP context flag is determined. In the whole process, if any step occurs error, the system will release all the resources applied and created, and return NULL pointer. Finally, when all steps are successfully executed, return the initialized kcp_session_t pointer.

[0065] As a feasible embodiment, the session lookup step includes searching in the session hash table according to the session identifier to obtain the corresponding KCP session. The session hash table is stored and retrieved by the session identifier as the key, realizing O(1) time complexity of session positioning. In high concurrency scenarios, this search method can greatly shorten the time required for session positioning, enabling the system to quickly respond to a large number of session requests.

[0066] Figure 3 A session lookup process schematic diagram is shown.

[0067] As Figure 3 shown, in the session lookup process, the system first calls the hash table lookup function, and performs matching operation through the session descriptor (conv), using the key value mapping characteristics of the hash table to quickly locate the target session. After completing the matching, return the corresponding kcp_session_t pointer according to the search result, and return NULL value if no matching item is found.

[0068] As a feasible embodiment, the data sending step includes sending data through the KCP session, calling the KCP protocol interface to encapsulate the data to be sent and issuing it through the output interface. When sending data, the system selects the corresponding transmission mode according to the input / output mode flag, if it is UDP mode, use the standard socket interface for network transmission. If it is a user-defined mode, call the user-specified input / output function to realize the data transmission in a specific scenario.

[0069] Figure 4 A flowchart of a session sending data is shown.

[0070] As shown in Figure 4 the session sending data flow, the system first calls the sending data method and checks the parameter legality. If the parameters are legal, the session is locked to ensure thread safety. Then it is determined whether the session is valid: if not, an error return value is set and the session is directly unlocked, and finally the sending data length is returned. If it is valid, ikcp_send is called to send data using the KCP protocol. If ikcp_send returns success, ikcp_flush will be further called to speed up data sending, and after completion, the session is unlocked and the sending data length is returned. If ikcp_send returns failure, the session is directly unlocked and the sending data length is returned. The entire flow is guaranteed by the locking operation to ensure the consistency of the session state, and the effectiveness judgment and error handling mechanism ensures the data integrity in abnormal scenarios, and finally the sending data length is returned as the execution result.

[0071] As a feasible embodiment, the data receiving step includes receiving data through the KCP session, calling the KCP protocol interface to parse the received data packet and extract the payload. The event polling receiving thread is responsible for listening to input and output events, and triggers data receiving processing when data arrives. The system parses the data packet through the KCP protocol interface and extracts valid data for use by the upper layer application.

[0072] Figure 5 A flowchart of a session receiving data is shown.

[0073] As shown in Figure 5 the session receiving data flow, the system first starts the receiving data method and checks whether the session has been locked (through the mutex). If it has not been locked, it directly returns an error value -1. If it has been locked, it further judges the validity of the session. When the session is invalid, the system sets an error return value and immediately unlocks the session, and then ends the receiving flow. When the session is valid, ikcp_recv is called to receive the data payload transmitted by the KCP protocol, and after completing the data receiving, the session is unlocked and the actual received data length is returned. This flow realizes thread safety protection through the mutex, ensures the legality of the operation through the validity check, and finally guarantees the controllability of the flow in abnormal scenarios through the case-by-case processing mechanism, completely covering all key steps from locking to returning the result.

[0074] As a feasible embodiment, the session release step includes releasing the KCP session no longer in use and removing it from the session hash table and the active session linked list. Session release usually occurs when the session times out or the application actively closes the session. The system updates the session state through atomic operations to ensure the safety of session release in a multi-threaded environment. Session state changes include updates to the validity flag and the last active time, effectively preventing race conditions in session state in a multi-threaded environment.

[0075] Figure 6 A session release flowchart is shown.

[0076] As Figure 6 shown, in the session release flow, the system first determines whether the session is valid. If not, it returns an error directly. If valid, it locks the session and sets the session state to invalid. Then it checks whether the session's file descriptor is the main listening fd. If not, it cancels the epoll listening. Next, it deletes the session entry from the session hash table and removes the related node from the active session linked list, completing the double-linked list management of the session. Then it releases the KCP protocol control block resources, unlocks the session to remove thread safety protection, destroys the session mutex and releases the session memory space, and finally returns the session release result. The entire process ensures the safe recovery of session resources and completely avoids memory leaks through validity verification, hierarchical processing of resource release, and coordinated operation of multiple data structures.

[0077] In some embodiments, the session management system runs at least three threads: a KCP update thread for periodically updating the status of all active KCP sessions, an idle detection thread for detecting and recycling KCP sessions that have been inactive for a long time, and an event polling reception thread for listening to input and output events and triggering data reception processing. The KCP update thread periodically calls ikcp_update to update all session states, ensuring the normal operation of the protocol. The idle detection thread periodically detects and recycles timeout sessions to prevent resource leaks. The event polling reception thread efficiently processes I / O events. The three threads have clear division of labor, avoiding task overlap and resource competition, so that the system can still maintain a stable and efficient running state under high load.

[0078] As a feasible embodiment, the KCP update thread uses a nanosecond-level sleep function for precise time control, ensuring that the thread is accurately executed at the predetermined period, effectively avoiding time accumulation errors, and improving the accuracy of system time management, providing a reliable guarantee for the stable operation of the KCP protocol.

[0079] As a specific embodiment, the input / output mode flag supports a UDP mode and a user-defined mode. In the UDP mode, the system directly uses a system socket interface for network transmission. In the user-defined mode, the system implements data transmission of specific scenarios through a user-specified input / output function, so that the KCP protocol can be flexibly adapted to different platforms and transmission requirements, and can not only use a standard socket interface for network transmission, but also implement data transmission of specific scenarios through a custom input / output function.

[0080] For example, when the system needs to run in a non-network environment, the user can specify a custom input / output function, so that the KCP protocol is not only applicable to traditional network environments, but also can be extended to be applied to cross-platform or custom protocol data transmission fields, greatly widening the application range and practicality of the KCP protocol.

[0081] In some embodiments, the session hash table adopts a bucket locking mechanism, each hash bucket is equipped with an independent mutex, and only when an add, delete, modify or query operation is performed, the hash bucket corresponding to the add, delete, modify or query operation is locked, avoiding the performance bottleneck caused by global locking, allowing multiple threads to operate different hash buckets at the same time, effectively improving the system concurrent processing capability and resource utilization.

[0082] The present application provides a session management method based on KCP protocol, through the cooperative work of session hash table and active session linked list, cooperating with the multi-thread cooperative mechanism of KCP update thread, idle detection thread and event polling receiving thread, the efficient creation, search, data sending and receiving and release process of session are realized, effectively solving the low efficiency of session management and resource competition problem in high concurrency scene in traditional KCP application, significantly improving the system processing capacity and stability.

[0083] In some embodiments, the session hash table is used to store KCP session pointers with session identifiers as keys, realizing O(1) time complexity of session search.

[0084] In some embodiments, the active session linked list is a double-linked list structure, supporting a first-in-first-out queue management, used to cache recent active sessions, supporting session pop-up operations in non-blocking, blocking and timeout modes.

[0085] In some embodiments, a session hash table is used to store KCP session pointers with session identifiers as keys, achieving O(1) time complexity of session lookup. The session hash table adopts a bucket locking mechanism, each hash bucket is equipped with an independent mutex, and only the hash bucket corresponding to the operation is locked when the add, delete, modify and query operations are performed. This design avoids the performance bottleneck caused by global locking, allows multiple threads to operate different hash buckets at the same time, effectively improves the system's concurrent processing capacity and resource utilization. The session hash table also implements a load factor statistics and automatic expansion mechanism, which tries to ensure that the depth of each hash table is 1, ensuring the efficiency of the hash table lookup.

[0086] Figure 7 A flowchart of hash table management is shown.

[0087] As shown in Figure 7 , based on hash table management, the session lookup process, session addition process and session deletion process are implemented through the following processes.

[0088] As a feasible embodiment, the session lookup process includes the following steps: calculating the hash value of the session identifier, obtaining the corresponding hash bucket pointer according to the hash value, locking the related hash bucket, traversing the nodes in the hash bucket, if the matching is successful, unlocking the hash bucket and returning the search result, if the matching is not successful, continue to traverse or return the result not found. This process realizes O(1) time complexity of session positioning through hash value calculation and hash bucket locking, greatly shortens the time required for session positioning in high concurrency scenarios, enabling the system to quickly respond to a large number of session requests.

[0089] As a specific embodiment, the session addition process includes the following steps: first, find the KCP session corresponding to the session identifier, if it exists, return the existing one, otherwise allocate hash node memory and save the node information, calculate the hash value of the session identifier, obtain the corresponding hash bucket pointer according to the hash value, lock the related hash bucket, add the hash node to the hash table and update the node count, unlock the hash bucket, and return the addition result. In high concurrency scenarios, the session addition operation ensures thread safety through the bucket locking mechanism, avoiding data competition caused by multiple threads modifying the same hash bucket at the same time.

[0090] As a specific embodiment, the session deletion process includes the following steps: in the session deletion process, the system first calculates the hash value of the session identifier, obtains the corresponding hash table pointer according to the hash value, then locks the target hash bucket for protection, then traverses each node in the hash bucket, if a matching node is found, it is deleted from the hash table and the node count is updated, then the memory of the hash node is released. If no matching node is found, continue to traverse the next node until all nodes are checked, and finally unlock the hash bucket and return the deletion result.

[0091] In some embodiments, the active session linked list is a double-linked list structure, supporting a first-in-first-out queue management for caching recent active sessions, and supporting session pop operations in non-blocking, blocking and timeout modes. The active session linked list is implemented in a double-linked list structure, supporting O(1) time complexity of head insertion and tail deletion operations. The double mutex lock mechanism is used to protect the linked list data and condition variable, improving concurrent performance. The condition variable synchronization mechanism is integrated in the linked list, supporting the wait / notify mode with timeout, avoiding busy waiting, and improving system resource utilization efficiency.

[0092] Figure 8 A flowchart of an active session management is shown.

[0093] As shown in Figure 8 Based on the active session linked list, the session addition flow, the session pop flow, the session timeout pop flow, and the session push flow are implemented as follows.

[0094] As a feasible embodiment, the session addition flow of the active session linked list includes the following steps: checking whether the number of nodes reaches the upper limit while holding the linked list lock, if not, allocating node memory and saving session information, locking the linked list, adding the node to the tail of the linked list and updating the node count, unlocking the linked list, and returning the addition result. This flow ensures the thread safety and efficiency of the session addition operation in a high-concurrency environment.

[0095] As a specific embodiment, the session pop flow of the active session linked list includes the following steps: locking the linked list, obtaining session information, deleting the node from the head of the linked list and updating the node count, releasing the node memory, unlocking the linked list, and returning the session information. This flow supports session pop operations in non-blocking, blocking and timeout modes, allowing the system to flexibly handle active sessions according to actual needs. For example, when the system needs to efficiently manage active sessions in a high-concurrency scenario, the session pop operation can use the blocking mode to wait for the session, and the thread synchronization is achieved through the condition variable mechanism, avoiding CPU resource waste caused by busy waiting. At the same time, the system supports the timeout pop mode, allowing the thread to wait for the session within a specified time, and if the timeout occurs, it will automatically return, improving the response speed and resource utilization efficiency of the system under high load.

[0096] In some embodiments, the session timeout pop flow of the active session linked list includes the following steps: locking the linked list, if the timeout time is 0, waiting to be woken up by the session push, otherwise setting the timeout time to wait for timeout or be woken up by the session push, unlocking the linked list, calling the session pop, and returning the session information. This flow supports timeout control, allowing the system to handle active sessions within a specific time, avoiding system resource occupation problems caused by long waiting time.

[0097] As a feasible embodiment, the session push-in process of the active session linked list includes the following steps: calling the session adding process, locking the condition variable, sending the condition variable signal to wake up the thread waiting for pop-out, unlocking the condition variable, and returning the push-in result. The process realizes the synchronization between session adding and session pop-out through the condition variable mechanism, ensuring efficient management of the active session linked list.

[0098] The application provides a KCP protocol-based session management method, which realizes efficient updating of session states, timely recycling of timeout sessions, and efficient processing of data reception through the multi-thread cooperative work of a KCP updating thread, an idle detection thread, and an event polling receiving thread, effectively solves the problem of low multi-thread cooperation efficiency in traditional KCP applications, and significantly improves the processing capacity and stability of the system in a high concurrency scenario.

[0099] In some embodiments, the KCP updating thread traverses the session hash table at a fixed time interval and calls the KCP updating function to update each session. The thread ensures the normal operation of the KCP protocol by periodically performing session state updating. After the KCP updating thread initializes the time interval, it checks the thread running flag. If it is valid, it traverses all the session hash tables, locks each hash bucket, acquires the current time, judges whether the session is valid, locks the valid session, calls the KCP updating function to update the session state, unlocks the session after completion, and continues to process the next session. After traversing all the hash tables, a nanosecond-level sleep function is used to accurately control the sleep time, reducing CPU occupation, and then the state updating process is continued.

[0100] As a feasible embodiment, the implementation process of the KCP updating thread includes: initializing the KCP updating time interval, checking the thread running flag, traversing all the session hash tables, locking each hash bucket in the hash table, acquiring the current time, judging whether the session is valid, locking the valid session, calling the KCP updating function to update the session after locking, unlocking the session and continuing to process other sessions in the current hash bucket, unlocking the hash bucket after traversing the current hash bucket, if there are still hash tables, continue to traverse, otherwise use the nanosecond-level sleep function to sleep, then recheck the thread running flag and continue to perform the updating operation. The process ensures that the KCP updating thread can stably and efficiently maintain the states of all active sessions in a high concurrency scenario.

[0101] Figure 9 A schematic diagram of a KCP updating thread is shown.

[0102] As Figure 9As shown in the execution flow of the KCP update thread, the system first checks whether the thread parameters are empty. If so, the system exits the running directly. If the parameters are valid, the system initializes the time interval of KCP update. Then the system checks the thread running flag. If the flag is invalid, the system terminates the thread. If the flag is valid, the system enters the session state update flow. The system traverses all session hash tables and processes each hash bucket in the hash table one by one. In the traversal process, the target hash bucket is locked, the current time is obtained, and it is determined whether the session is valid. For a valid session, the session is locked and the ikcp_update function is called to update the session state, and then the session is unlocked. If the session is invalid, the processing is skipped directly. After the traversal of the current hash bucket is completed, the hash bucket is unlocked, and it is determined whether other hash tables need to be processed. When all hash tables are traversed, the nanosleep is used for accurate sleep to reduce the CPU occupancy, and then the thread running flag is checked again to determine whether to continue the next round of update.

[0103] As a specific embodiment, the nanosecond-level time control mechanism of the KCP update thread realizes accurate time interval control by using a nanosecond-level sleep function, avoids time accumulation error, and ensures that the thread is accurately executed according to the predetermined period. In the implementation, after completing a round of session state update, the KCP update thread uses the nanosecond-level sleep function for accurate sleep instead of simple microsecond-level sleep, thereby effectively avoiding time accumulation error and improving the accuracy of system time management, providing a reliable guarantee for stable operation of the KCP protocol.

[0104] In some embodiments, the idle detection thread periodically checks the last activity time of the session, and triggers the session release if the timeout occurs. After the thread initializes the sleep time interval, it checks the thread running flag. If the flag is valid, the thread sleeps using the nanosecond-level sleep function, and then determines whether the idle session detection flag is enabled. If the flag is enabled, the thread traverses all session hash tables, locks each hash bucket, obtains the current time, and determines whether the session meets the timeout condition. For the timeout session, the hash bucket is unlocked, the session is released, the hash bucket is relocked, and the processing continues. After traversing all sessions, the hash bucket is unlocked. If there are still hash tables, the traversal continues. Otherwise, the sleep operation continues. This mechanism effectively prevents resource leakage and ensures that the system can maintain a stable and efficient running state under high load.

[0105] As a feasible embodiment, the session timeout detection process of the idle detection thread includes: initializing a sleep time interval, checking a thread running flag, sleeping using a nanosecond-level sleep function, judging whether an idle session detection flag is enabled, if enabled, traversing all session hash tables, locking a hash bucket in each hash table, obtaining a current time, judging whether a session meets a timeout condition, if yes, unlocking the hash bucket, releasing the timeout session, relocking the hash bucket, otherwise, continuing to process other sessions in the current hash bucket, unlocking the hash bucket after the current hash bucket is traversed, if there are still hash tables, continuing to traverse, otherwise, continuing to perform the sleep operation. The process ensures that the timeout session can be detected and released in time by regularly checking the last active time of the session, effectively avoiding the memory leakage problem.

[0106] As a specific embodiment, the timeout condition judgment of the idle detection thread is based on the difference between the last active time of the session and the current time, and when the difference exceeds a preset timeout threshold, the session is considered to be timeout. In actual application, the system maintains a last active time field of the session, updates the field each time the session is active, and the idle detection thread regularly checks the difference between the field and the current time, and if the difference exceeds the set threshold, triggers the session release, ensuring efficient use of system resources.

[0107] Figure 10 A flowchart of KCP idle session detection is shown.

[0108] In the execution process of the idle session detection thread, the system first initializes a sleep time interval and checks a thread running flag: if the flag is valid, the thread enters a sleep state (the sleep time is accurately controlled by nanosleep to reduce CPU occupation), if the flag is invalid, the thread directly exits the running. When the sleep ends, the system judges whether the KCP_FLAG_IDLE_SESSION flag is enabled, if enabled, the system starts to traverse all session hash tables and obtains a current time. Then, the system locks a hash bucket in each hash table for protection, and checks whether a session meets a timeout condition. If the session is timeout, the system first unlocks the hash bucket and releases the session resource, and then relocks the hash bucket to ensure thread safety. If the session is not timeout, the system directly unlocks the hash bucket. After the processing of the current hash bucket is completed, the system judges whether other sessions or hash tables need to be processed, if there are still unprocessed items, the system repeats the above process, otherwise, the system returns to check the thread running flag, forming a loop execution mechanism. The whole process controls the function enablement through a flag bit, guarantees concurrent safety through bucket locking, optimizes resource occupation through accurate sleep, and finally realizes the periodic detection and release of the timeout session.

[0109] In some embodiments, the event polling receiving thread listens to socket events based on the event polling mechanism, and calls the KCP data input function for processing when data is received. After the thread initializes the event polling related variables, it checks the thread running flag. If valid, it waits for events to occur. If there are events, it traverses all events, calls the KCP data input function for data reception for EPOLLIN events, and processes other events for EPOLLERR or EPOLLUP events. After completion, it waits for events again. This mechanism enables the system to efficiently process I / O events and avoid resource waste caused by blocking I / O operations.

[0110] As a feasible embodiment, the implementation process of the event polling receiving thread includes: initializing the epoll event and related variables, checking the thread running flag, waiting for events to occur, traversing all events if there are events, calling the KCP data input function for data reception for EPOLLIN events, and processing other events for EPOLLERR or EPOLLUP events. After traversing all events, it waits for events again. This process efficiently processes network data through event-driven mode, ensuring that the system can respond to the arrival of network data packets in a timely manner.

[0111] As a specific embodiment, when the event polling receiving thread processes EPOLLIN events, it calls the KCP data input function to pass the received data packet to the KCP protocol stack for parsing and processing. The KCP data input function is responsible for converting the original data packet into a KCP internal data structure, performing data packet verification and processing, and then triggering the corresponding data reception process. In a high-concurrency scenario, this mechanism can effectively process a large number of network data packets and avoid the performance bottleneck caused by traditional blocking I / O.

[0112] For example, when the system needs to process a large number of real-time data packets, the event polling receiving thread efficiently listens to socket events through the epoll mechanism, and immediately triggers the KCP data input function for processing when data arrives, without waiting for all data packets to arrive, significantly improving the real-time performance of data reception and system throughput. At the same time, this mechanism supports multiple network event types and can flexibly adapt to data reception requirements in different network environments.

[0113] Figure 11 A flowchart of an epoll receiving thread is shown.

[0114] As Figure 11As shown in the execution flow of the epoll receiving thread, the system first initializes the epoll event and related variables, and then checks the thread running flag: if the flag is valid, it continues to execute, otherwise it directly exits the thread. After entering the event waiting state, if an event is detected, it continues to be processed, otherwise it returns to check the thread running flag. In the event processing stage, the system first judges whether there is an error: if there is no error, it enters the event traversal process, otherwise it directly exits the thread. When traversing the event, if the event type is EPOLLIN, the kcp_input processing data receiving is called. If the event type is EPOLLERR or EPOLLUP and the event source is the main listening file descriptor, the thread exit is triggered. After completing the current event processing, the system judges whether there are still unprocessed events: if there are, it continues to traverse, otherwise it returns to check the thread running flag, forming a loop mechanism. This flow realizes efficient I / O processing through event-driven mode, combines the main listening fd abnormality detection mechanism to guarantee thread safety, and finally realizes the flexible switching of dynamic exit and continuous running through the flag bit control.

[0115] The application provides a KCP protocol-based session management method, which realizes efficient creation, searching, data sending and receiving and release process of the session through the cooperative work of the session hash table, the active session linked list and the atomic operation, effectively solves the low efficiency of session management and resource competition problems in the high concurrency scene of the traditional KCP application, and significantly improves the system processing capacity and stability.

[0116] In some embodiments, the change of the session state is realized through the atomic operation, including the update of the session validity flag and the last active time, which ensures the thread-safe session creation, searching and release.

[0117] As a feasible embodiment, the change of the session state is realized through the atomic operation, including the update of the session validity flag and the last active time. The session validity flag is used to indicate whether the session is in a valid state, and the last active time is used to record the time of the last activity of the session. In the implementation, the system initializes the validity flag as valid and the last active time as the current time when creating the session. When the session performs data interaction, the last active time is updated to the current time. When the session needs to be released, the validity flag is set to invalid. These state changes are realized through the atomic operation, which ensures that the change of the session state in the multi-threaded environment will not occur in a race condition, and guarantees the thread safety of the session state management.

[0118] In some embodiments, the update of the session validity flag and the last activity time is completed through atomic operations, and the implementation includes: when it is necessary to update the session state, an atomic operation function is called to atomically compare and exchange the new value with the old value, so as to ensure the atomicity of the state update. For example, when updating the last activity time, the system obtains the current time, and calls an atomic operation function to set the current time as the last activity time of the session. The operation guarantees the atomicity of the operation at the hardware level, avoiding errors in the last activity time caused by concurrent updates in a multi-threaded environment.

[0119] For example, when multiple threads simultaneously operate on the same session, the atomic operation ensures that the changes in the session state are executed in sequence. For example, when one thread is updating the last activity time of the session and another thread simultaneously attempts to release the session, the atomic operation ensures that the update and release operations do not interfere with each other, ensuring the consistency of the session state. The system updates the session state through atomic operations, avoiding the performance bottleneck caused by the traditional lock mechanism and improving the response speed and resource utilization efficiency of the system in a high-concurrency scenario.

[0120] In some embodiments, the input / output mode flag supports at least one of a UDP mode and a user-defined mode. The UDP mode uses a socket interface for data transmission and reception, and the user-defined mode uses a user-provided input / output function for data transmission and reception.

[0121] Figure 12 An operation thread diagram of an input / output extension interface is shown.

[0122] As shown in Figure 12 , the input / output mode flag is implemented by setting the KCP_FLAG_FD_UDP and KCP_FLAG_FD_USER flags, where the KCP_FLAG_FD_UDP flag indicates the use of a socket interface for data transmission, and the KCP_FLAG_FD_USER flag indicates the use of a user-provided input / output function for data transmission. When the input / output mode flag is set to the UDP mode, the system performs data transmission and reception through the recvfrom and sendto functions. When it is set to the user-defined mode, the system calls the user-specified input / output function for data processing. This design enables the system to flexibly adapt to different platforms and transmission requirements, improving the adaptability and expandability of the system.

[0123] As a feasible embodiment, the implementation of UDP mode is based on system socket interface. When the input / output mode flag is set to UDP mode, the system detects the position of KCP_FLAG_FD_UDP flag in the kcp_input data receiving process and uses the recvfrom function to receive data. In the kcp_output data sending process, the system detects the position of KCP_FLAG_FD_UDP flag and uses the sendto function to send data. In the data receiving process, the system finds the session through the session identifier. If the session exists, the last active time is updated, the ikcp_input process is scheduled to process data, and the session is pushed into the active session linked list. In the data sending process, the system directly sends data through the sendto function without additional processing, ensuring the efficiency of network data transmission.

[0124] In some embodiments, the user-defined mode is adapted to non-network transmission scenarios, and the input / output function is configured to perform cross-platform or custom protocol data transmission.

[0125] As a specific embodiment, the implementation of user-defined mode is achieved by setting the KCP_FLAG_FD_USER flag and canceling the KCP_FLAG_FD_UDP flag. When the input / output mode flag is set to user-defined mode, the system detects the position of KCP_FLAG_FD_USER flag in the kcp_input data receiving process and calls the user-provided input function to receive data when the input function is valid. In the kcp_output data sending process, the system detects the position of KCP_FLAG_FD_USER flag and calls the user-provided output function to send data when the output function is valid. In this mode, users can implement custom data transmission logic according to specific requirements, such as adapting to non-network transmission scenarios or specific hardware device communication protocols.

[0126] In some embodiments, the input / output function of the user-defined mode is configured to adapt to non-network transmission scenarios and perform cross-platform or custom protocol data transmission. For example, when the system needs to perform data transmission in memory, users can provide custom input / output functions to store data in memory buffers instead of sending data over the network. In the implementation, users set the input / output function pointers, and the system automatically calls these functions when it detects the KCP_FLAG_FD_USER flag without modifying the core KCP protocol code, greatly improving the flexibility and scalability of the system.

[0127] For example, when the system needs to implement the KCP protocol on an embedded device, the user can provide a custom input and output function to transmit data through a serial port or a specific hardware interface instead of using a standard network socket. In a specific implementation, the user-defined input function can read data from the serial port, and the output function can write data to the serial port, and the KCP protocol stack does not need to know these details, and only needs to call the user-provided function to complete the data transmission. This design makes the KCP protocol not only suitable for traditional network environments, but also extends its application to the field of cross-platform or custom protocol data transmission, greatly expanding the application range and practicality of the KCP protocol.

[0128] The application also provides a system embodiment matched with the above embodiment, which comprises a session management module for implementing the method steps of the above embodiment, has the same technical effects as the above embodiment based on the same interpretation of the same name meaning, and will not be described here.

[0129] As shown in Figure 13 The application provides a session management system based on a KCP protocol, which comprises:

[0130] The session management module 130 comprises:

[0131] The session hash table unit 1301 is configured to store the mapping relationship between the session identifier and the session object.

[0132] The active session linked list unit 1302 is configured to maintain recent active sessions.

[0133] The multi-thread scheduling unit 1303 is configured to manage the creation and cooperation of the KCP update thread, the idle detection thread, and the event polling receiving thread.

[0134] The input and output adaptation unit 1304 is configured to select a data transceiving mode according to a flag bit.

[0135] The system is configured to run on a server or a client device supporting the KCP protocol.

[0136] The session hash table adopts a bucket locking mechanism, each hash bucket is equipped with an independent mutex, and only the hash bucket corresponding to the add, delete, modify, and query operation is locked when the add, delete, modify, and query operation is performed.

[0137] Figure 14 A creation flowchart of a session management system based on a KCP protocol is shown.

[0138] As shown in Figure 14As shown, in the session management system creation process, first, context memory is allocated for managing the session system, and the KCP window size is initialized (which can be dynamically set through a function interface), then the session hash table is initialized to support fast lookup, session update and timeout cleaning functions, and the active session list is initialized for sorting and buffering active sessions. Then save the listener file descriptor for the epoll receive thread to listen, and set the thread running flag to control the start and stop of the thread. The system further saves the KCP context flag bit, creates an epoll file descriptor to realize efficient I / O monitoring, and registers the main listener file descriptor to the epoll instance. Then create three core threads in turn: the KCP update thread is used to periodically call ikcp_update to maintain the session state, the idle detection thread is used to check and clean up the timeout session, and the epoll receive thread is used to efficiently receive data. If the above initialization process is successful, return the kcp_context_t pointer of the initialization completion. If any step fails, the system will cancel the thread running flag and wait for the thread to end, close the epoll file descriptor, release the listener table and registry table resources, and finally release the context memory and return NULL. This process ensures the stability and resource safety of the system in abnormal scenarios through phased initialization and resource recycling mechanism.

[0139] Figure 15 A release process schematic diagram of a session management system based on KCP protocol is shown.

[0140] In the session management system release process, the system first checks the validity of the KCP context pointer, and if the pointer is invalid, the process is terminated directly. If the pointer is valid, set the thread running flag to the cancel state. Then process each thread in turn: if the KCP update thread exists, cancel its running and wait for the thread to end. If the idle detection thread exists, also cancel and wait for the thread to end. If the epoll receive thread exists, cancel its running and wait for the thread to end. After completing the thread processing, the system checks the validity of the epoll file descriptor, and if it is valid, closes the descriptor. Then enter the resource release phase: if the session hash table exists, release the memory it occupies. If the hash table does not exist, further check whether the active session table exists, and if it exists, release the active session table. Finally, release the KCP context memory, complete the resource recycling of the entire system and exit the process. This process ensures the safe recycling of resources and system stability in a multi-threaded environment through layer-by-layer judgment and ordered release mechanism.

[0141] Figure 16 A whole process schematic diagram of a session management method and system based on KCP protocol is shown.

[0142] As Figure 16As shown, the KCP protocol-based session management method and system implementation process can be summarized as the following three parts: (1) Session management system process, including: after system initialization, task allocation and management are realized through multi-thread cooperation, including KCP update thread (periodic call ikcp_update), idle detection thread (timeout session cleaning) and epoll receiving thread (efficient I / O event processing). At the same time, the hash session table realizes O(1) time complexity of session search and management through the bucket locking mechanism, the active session linked list supports dynamic maintenance of the active session queue, and through the IO expansion interface, the UDP mode or the user-defined input and output function is adapted to realize cross-platform data transmission. (2) Session management method process: the specific method includes session creation (initialization control block, setting window size and MTU, registering to hash table and active linked list), session release (unlocking resources, deleting hash table node, cleaning linked list), session search (locating session through hash value), sending data (locking call ikcp_send and ikcp_flush) and receiving data (locking call ikcp_recv). The above processes are guaranteed to be thread-safe through atomic operation and mutual exclusion. (3) KCP protocol implementation, including: based on the ikcp framework, the message encapsulation sending and receiving decapsulation process are realized, and optimization is carried out for the architecture, and the sending / receiving window size is supported. It needs to be explained that the present application focuses on the KCP protocol-based session management method and system, and the KCP protocol implementation is not described in the present application. In the above embodiment, through multi-thread cooperation, efficient data structure and protocol optimization, the stability of session management and the improvement of data transmission performance in a high-concurrency scenario are realized.

[0143] Figure 17 A use flow example diagram of the KCP protocol-based session management method and system is shown.

[0144] As shown in the above Figure 17 , the interaction process of the KCP protocol-based session management method and system between the server and the client is as follows.

[0145] Server process: the server first initializes the UDP socket file descriptor and binds the service address and port, and then initializes the session management system (sets the flag to KCP_FLAGS_SERVER and enables the active session linked list). After obtaining the session to be processed by calling the active session pop-up method, the session receives data method is used to read the client request data, the service logic (such as echo service returns the data as it is) is executed, and the response data is sent to the client through the session sends data method. If continuous service is required, the session pop-up and data transmission process is repeated. If the service is exited, the session management system release method is called to terminate the session management.

[0146] Client process: After the client initializes the UDP socket file descriptor, the session management system is initialized (the flag bit is set to KCP_FLAGS_CLIENT), and the connection with the server is established through the active session creation method. Then the session data sending method is called to send request data to the server, and the session data receiving method is called to obtain the response data of the server. If interaction continues, the sending and receiving process is repeated. If the request is terminated, the session management system release method is called to exit.

[0147] In the above embodiment, the kcp_input and kcp_output interfaces are responsible for the underlying data scheduling, ensuring reliable transmission of data between the server and the client in the network environment, and managing the session life cycle through the active session linked list, realizing efficient service interaction and resource release.

[0148] The embodiment of the application provides a session management method and a multi-thread cooperative optimization system based on a KCP protocol, which is used for providing high reliability, high concurrency and low latency data transmission services in a connectionless and unreliable UDP network environment, and can be applied to reliable data transmission scenes in non-network fields.

[0149] In some embodiments, the system realizes efficient organization and scheduling of KCP sessions through a multi-dimensional session management mechanism. Specifically, a hash table structure is used to manage KCP sessions with session identifiers (conv) as keys, realizing O(1) time complexity of session search function. The active session linked list is maintained by FIFO mechanism, which is used for queuing and caching active sessions. The session life cycle is managed by atomic operation throughout the session state, ensuring the thread safety of session creation, search and release operations.

[0150] As a feasible embodiment, the system sets three core working threads to realize multi-thread cooperative processing. The KCP update thread periodically calls the ikcp_update function to update the state of all active sessions. The idle detection thread periodically detects and recycles sessions that have been inactive for a long time, preventing resource leakage. The I / O event listening thread listens to and processes input and output events based on the epoll mechanism. In addition, high-precision sleep functions (such as nanosleep) are used to realize precise time control, ensuring that each thread executes according to the predetermined period, and avoiding the accumulation of time errors.

[0151] As a specific embodiment, the system provides an extensible input and output interface, which supports multiple data transmission modes through a flag bit mechanism. For example, in the UDP mode, the system socket interface is directly called for data transmission and reception. In the user-defined mode, the user can register a custom input and output function, so as to adapt to the needs of different platforms or non-network transmission scenes.

[0152] The embodiment of the present application also discloses a session management system, core components of which include a KCP context (kcp_context_t) and a KCP session (kcp_session_t). The KCP context is used for managing system-level resources, including threads, hash tables, active session linked lists, input and output interfaces and context identifiers. The KCP session is used for representing a single connection and provides interfaces related to session creation, search, data sending, data receiving and release.

[0153] In some embodiments, the session hash table adopts a bucket locking mechanism to improve concurrent performance, each hash bucket is equipped with an independent mutex, and only the corresponding hash bucket is locked when the adding, deleting, modifying and searching operation is performed. The active session linked list is implemented by using a double-linked list structure, supports session pop-out operations in various modes such as non-blocking, blocking and timeout, and realizes efficient synchronization through a condition variable mechanism.

[0154] The present application realizes the following beneficial effects through the above-mentioned mechanism: the efficient session management mechanism significantly improves the processing efficiency in a high-concurrency scenario. The multi-threaded division mechanism reduces resource competition and improves the overall performance of the system. The flexible input and output interface enhances the cross-platform adaptation capability of the system. The perfect session life cycle management and thread synchronization mechanism effectively prevent resource leakage and protect the safety of system resources.

[0155] As to the system in the above-mentioned embodiment, the specific manner in which each module performs operations has been described in detail in the embodiment related to the method, and will not be described in detail here.

[0156] Although the operations are described in a particular, sequential order, it should be appreciated that some of the operations described do not need to be performed in the exact order described, or in any prescribed order, unless the order is explicitly required by the preceding claims. For example, it is possible in some implementations for two or more of the above-described operations to be performed substantially concurrently, or in some cases in a slightly different order.

[0157] The methods and systems of the present application can be implemented using standard programming techniques, which, as will be appreciated by those skilled in the art, can be implemented using one or more software programs and / or hardware modules. Furthermore, the described embodiments can be implemented using any suitable programming medium or programming technique for example, software, firmware, hardware, discrete logic, etc.

[0158] Any of the steps, operations, or procedures described herein can be performed or implemented using one or more hardware or software modules, alone or in combination with other devices. In one implementation, a software module is implemented using a computer program product comprising a computer readable medium containing computer program code, which can be executed by a computer processor for performing any or all of the steps, operations, or procedures described.

[0159] The foregoing description of the implementations has been presented for the purposes of illustration and description. It is not intended to be exhaustive or to limit the application to the precise form disclosed. Many modifications and variations are possible in light of the above teaching. It is intended that the scope of the application be limited not with this detailed description, but rather by the claims appended hereto.

[0160] With regard to the systems in the above-described embodiments, in which the specific manner in which the various modules perform operations has been described in detail in connection with the methods of the embodiments, the detailed description thereof will not be repeated here.

[0161] It should be further understood that a connection between two elements is not limited to a direct connection, unless otherwise specified, and can also include an indirect connection between two elements through other elements.

[0162] It should be further understood that, although the operations of the present embodiments have been described in a particular, sequential order, this order is not necessarily a required order. Also, some of the operations described in the embodiments herein can be handled in parallel, and implementation of a described process can be distributed over two or more physical devices.

[0163] Other embodiments of the application will be apparent to those skilled in the art from consideration of the specification and practice of the application disclosed herein. It is intended that the specification and examples be considered as exemplary only, with the true scope and spirit of the application being indicated by the following claims.

[0164] It is to be understood that the application is not limited to the precise details of construction and the exact construction and proportions herein described and illustrated, and that changes can be made in the precise apparatus disclosed and in the embodiments described herein without departing from the scope of the application. The scope of the application should, therefore, be determined not with reference to the above description, but should instead be determined with reference to the appended claims, along with their full scope of equivalents.

[0165] The above embodiments are only used to illustrate the technical solutions of the present application, not limit the present application; although the present application has been described in detail with reference to the foregoing embodiments, those ordinarily skilled in the art should understand: the technical solutions recorded in the foregoing embodiments can be modified, or some technical features can be replaced equivalently; and the modification or replacement 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 application.

Claims

1. A method for session management based on KCP protocol, characterized in that, The method comprises the following steps: a session management system initialization step, including creating and initializing a KCP context, the KCP context including a session hash table, an active session linked list, a thread control flag and an input / output mode flag; a session creation step, including creating a KCP session based on a received data packet and assigning a session identifier to the KCP session, and storing the mapping relationship between the session identifier and the KCP session in the session hash table; a session lookup step, including looking up the session hash table according to the session identifier to obtain the corresponding KCP session; a data sending step, including sending data through the KCP session, calling a KCP protocol interface to encapsulate the data to be sent and issuing it through an output interface; a data receiving step, including receiving data through the KCP session, calling a KCP protocol interface to parse the received data packet and extract the payload; a session release step, including releasing a KCP session that is no longer in use and removing it from the session hash table and the active session linked list; wherein the session management system runs at least three threads: a KCP update thread for periodically updating the status of all active KCP sessions; an idle detection thread for detecting and recycling KCP sessions that have been inactive for too long; and an event polling receiving thread for listening to input / output events and triggering data receiving processing; wherein the session management system is implemented based on the KCP protocol, including implementing message encapsulation and sending and receiving decapsulation processes based on the ikcp framework, optimizing the architecture, supporting configuration of the sending and receiving window size, and expanding the upper limit of single sending data from KB level to MB level; wherein the session hash table uses a bucket locking mechanism, each hash bucket is equipped with an independent mutex, and only the hash bucket corresponding to the add, delete, modify and query operation is locked when the operation is performed.

2. The KCP protocol based session management method according to claim 1, wherein, The session hash table is used to store KCP session pointers with session identifiers as keys, and implements session lookup with O(1) time complexity.

3. The KCP protocol-based session management method of claim 1, wherein: the KCP update thread traverses the session hash table at a fixed time interval and calls a KCP update function to update each session; the idle detection thread periodically checks the last active time of a session, and triggers session release if it is timed out; the event polling receiving thread listens to socket events based on an event polling mechanism, and calls a KCP data input function to process when data is received.

4. The KCP protocol based session management method according to claim 1, wherein, The KCP update thread uses a nanosecond-level sleep function for time control.

5. The KCP protocol based session management method according to claim 1, wherein, Changes in session status are implemented through atomic operations, including updating the session validity flag and the last active time.

6. The KCP protocol based session management method according to claim 1, wherein, The input / output mode flag supports at least one of a UDP mode and a user-defined mode; wherein, for the UDP mode, a socket interface is used for data transmission and reception; for the user-defined mode, a user-provided input / output function is used for data transmission and reception.

7. The KCP protocol based session management method according to claim 6, wherein, For the user-defined mode, the input / output function is configured to adapt to non-network transmission scenarios and perform cross-platform or custom protocol data transmission.

8. The KCP protocol based session management method according to claim 1, wherein, The active session linked list is a bidirectional linked list structure, supports first-in first-out queue management, is used for buffering recent active sessions, and supports session pop operation in non-blocking, blocking and timeout modes.

9. A session management system based on KCP protocol, characterized by, The system comprises: a session management module configured to implement the KCP protocol-based session management method according to any one of claims 1 to 8; the session management module comprises: a session hash table unit configured to store a mapping relationship between a session identifier and a session object; an active session linked list unit configured to maintain recent active sessions; a multi-thread scheduling unit configured to manage creation and cooperation of a KCP update thread, an idle detection thread and an event polling receiving thread; an input / output adaptation unit configured to select a data transceiving mode according to a flag bit; wherein the system is configured to run on a server or a client device supporting the KCP protocol; wherein the session hash table adopts a bucket locking mechanism, each hash bucket is provided with an independent mutex, and when an adding, deleting, modifying or inquiring operation is performed, only the hash bucket corresponding to the adding, deleting, modifying or inquiring operation is locked.

Citation Information

Patent Citations

  • High-speed data acquisition and transmission improved KCP protocol for simulation training

    CN117938972A

  • KCP reliable transmission proxy method and system based on digital networking

    CN120281832A