### Quick Start: Connect and Exchange Data with KCP Source: https://docs.rs/kcp-tokio/latest/index.html This example demonstrates how to establish a KCP connection, send data, and receive a response using kcp-tokio. Ensure you have tokio and kcp-tokio dependencies added to your project. ```rust use kcp_tokio::{KcpConfig, KcpStream}; use std::net::SocketAddr; #[tokio::main] async fn main() -> Result<(), Box> { let addr: SocketAddr = "127.0.0.1:8080".parse()?; let config = KcpConfig::new().fast_mode(); let mut stream = KcpStream::connect(addr, config).await?; use tokio::io::AsyncWriteExt; stream.write_all(b"Hello, KCP!").await?; use tokio::io::AsyncReadExt; let mut buffer = [0u8; 1024]; let n = stream.read(&mut buffer).await?; println!("Received: {:?}", &buffer[..n]); Ok(()) } ``` -------------------------------- ### KcpEngine::start Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html?search=std%3A%3Avec Starts the KCP engine, preparing it for operation. ```APIDOC ## KcpEngine::start ### Description Start the engine. ### Method `start` ### Parameters None ### Returns - Result<(), KcpCoreError> - Ok if the engine started successfully, Err otherwise. ``` -------------------------------- ### KcpEngine::start Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html?search= Starts the KCP engine, initializing its internal state. ```APIDOC ## KcpEngine::start ### Description Starts the KCP engine, preparing it for operation. ### Signature `pub fn start(&mut self) -> Result<(), KcpCoreError>` ### Returns `Ok(())` if the engine started successfully, or a `KcpCoreError` on failure. ``` -------------------------------- ### KcpEngine::start Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts the KCP engine, preparing it for operation. This method should be called after initialization. ```APIDOC ## KcpEngine::start ### Description Starts the KCP engine. This method initializes the engine's internal state for operation. ### Signature `pub fn start(&mut self) -> Result<(), KcpCoreError>` ### Returns * `Ok(())` on successful start. * `Err(KcpCoreError)` if the engine fails to start. ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/error.rs.html?search= Illustrative search queries for exploring Rust standard library functionalities. ```Rust std::vec u32 -> bool Option, (T -> U) -> Option ``` -------------------------------- ### connect Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html Establishes a KCP connection to a specified address using the current KcpConfig. This is a convenience method that wraps the underlying stream and transport setup. ```APIDOC ## connect ### Description Establishes a KCP connection to a specified address using the current KcpConfig. This is a convenience method that wraps the underlying stream and transport setup. ### Method `async fn connect>(self, addr: A) -> Result>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let config = KcpConfig::default(); let stream = config.connect("127.0.0.1:1234").await; ``` ### Response #### Success Response - `KcpStream`: A successfully established KCP stream. #### Response Example ```rust // Success response is implicit upon successful `Ok` return. ``` #### Error Response - `KcpError`: If the configuration is invalid or connection fails. ``` -------------------------------- ### Start KCP Engine Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html?search=u32+-%3E+bool Initiates the KCP engine. This method should be called to begin the KCP protocol's operation. It returns a Result, indicating success or a KcpCoreError. ```rust pub fn start(&mut self) -> Result<(), KcpCoreError> ``` -------------------------------- ### BufferPool Methods Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/buffer_pool.rs.html?search=std%3A%3Avec Provides methods for creating, getting, putting, and retrieving statistics from a buffer pool. ```APIDOC ## BufferPool ### Description A high-performance lock-free buffer pool using crossbeam-queue for KCP packet allocation. ### Methods #### `new(max_size: usize, buffer_size: usize) -> Self` Creates a new buffer pool with a specified maximum number of buffers and individual buffer size. #### `try_get(&self) -> BytesMut` Attempts to retrieve a buffer from the pool. If the pool is empty, a new buffer with the configured `buffer_size` is allocated. This operation is lock-free. #### `try_put(&self, buf: BytesMut)` Attempts to return a buffer to the pool. Buffers are only accepted if their capacity is within a certain range relative to the pool's `buffer_size` to maintain efficiency. This operation is lock-free and ignores the push if the pool is full. #### `stats(&self) -> (usize, usize)` Returns statistics about the buffer pool, specifically the number of successful buffer retrievals ('hits') and the current number of buffers available in the pool. ``` -------------------------------- ### Convenience Listen Function for Tokio Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search=std%3A%3Avec Use this function to start listening for incoming KCP connections over UDP with Tokio. It takes an address and a KcpConfig, returning a KcpListener. ```rust pub async fn listen>( self, addr: A, ) -> Result> { self.validate()?; crate::listener::KcpListener::bind(addr.into(), self).await } ``` -------------------------------- ### Listen with KCP Tokio Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html Convenience function to start listening for KCP connections using Tokio. Requires the 'tokio' feature to be enabled. ```rust pub async fn listen>( self, addr: A, ) -> Result> { self.validate()?; crate::listener::KcpListener::bind(addr.into(), self).await } ``` -------------------------------- ### Unwrapping with `expect` for Environment Variables Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example of using expect to retrieve an environment variable, providing a clear error message if the variable is not set. This pattern emphasizes the expected state of the environment. ```Rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### UdpTransport Bind Example Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/transport.rs.html?search=u32+-%3E+bool Binds a new UDP socket to a specified address, creating a `UdpTransport` instance. This is the primary way to initialize the default transport. ```rust pub async fn bind(addr: impl tokio::net::ToSocketAddrs) -> io::Result { let socket = UdpSocket::bind(addr).await?; Ok(Self { socket }) } ``` -------------------------------- ### Start Background Listening Task Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/listener.rs.html?search= Initiates the background task responsible for listening for incoming UDP packets and managing KCP connections. It handles packet reception, new connection attempts, and periodic cleanup. ```rust async fn start_listening(&mut self) -> Result<()> { let transport = self.transport.clone(); let conn_state = self.conn_state.clone(); let active_streams = self.active_streams.clone(); let connection_sender = self.connection_sender.clone(); let handshake_timeout = self.config.connect_timeout; let max_pending = self.config.max_pending_connections; let cleanup_dur = self.config.cleanup_interval; self.listen_task = Some(tokio::spawn(async move { info!("Listener background task started, waiting for packets..."); let mut buf = vec![0u8; 65536]; let mut cleanup_interval = tokio::time::interval(cleanup_dur); loop { tokio::select! { // Receive incoming packets recv_result = transport.recv_from(&mut buf) => { match recv_result { Ok((size, peer_addr)) => { let data = Bytes::copy_from_slice(&buf[..size]); trace!("Received {} bytes from {}", size, peer_addr); // First check if this is from an active stream (lock-free lookup) if let Some(handle) = active_streams.get(&peer_addr) { let _ = handle.input_tx.try_send(data); continue; } // Not an active stream, handle as potential new connection if let Err(e) = Self::handle_incoming_packet( data, &peer_addr, &conn_state, &connection_sender, max_pending, ).await { trace!( peer = %peer_addr, error = %e, "Failed to handle incoming packet" ); } } Err(e) => { error!(error = %e, "UDP receive failed"); break; } } } // Periodic cleanup _ = cleanup_interval.tick() => { Self::cleanup_dead_streams(&active_streams, &conn_state).await; Self::cleanup_pending_connections(&conn_state, handshake_timeout).await; } } } })); Ok(()) } ``` -------------------------------- ### KcpListener::bind Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/listener/struct.KcpListener.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Binds a new KcpListener to a specific network address with a given KCP configuration. This is the primary way to start listening for incoming KCP connections. ```APIDOC ## pub async fn bind(addr: SocketAddr, config: KcpConfig) -> Result ### Description Binds to the specified address to create a new KcpListener. ### Method `async fn bind` ### Parameters - **addr** (`SocketAddr`) - The network address to bind the listener to. - **config** (`KcpConfig`) - The KCP configuration to use for the listener. ### Returns - `Result` - A `Result` containing the new `KcpListener` on success, or an error if binding fails. ``` -------------------------------- ### KCP Listener: Start Background Listening Task Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/listener.rs.html?search=std%3A%3Avec Initiates the background task responsible for listening for incoming packets and managing connections. It handles packet reception, new connection attempts, and periodic cleanup. ```rust /// Start the background listening task async fn start_listening(&mut self) -> Result<()> { let transport = self.transport.clone(); let conn_state = self.conn_state.clone(); let active_streams = self.active_streams.clone(); let connection_sender = self.connection_sender.clone(); let handshake_timeout = self.config.connect_timeout; let max_pending = self.config.max_pending_connections; let cleanup_dur = self.config.cleanup_interval; self.listen_task = Some(tokio::spawn(async move { info!("Listener background task started, waiting for packets..."); let mut buf = vec![0u8; 65536]; let mut cleanup_interval = tokio::time::interval(cleanup_dur); loop { tokio::select! { // Receive incoming packets recv_result = transport.recv_from(&mut buf) => { match recv_result { Ok((size, peer_addr)) => { let data = Bytes::copy_from_slice(&buf[..size]); trace!("Received {} bytes from {}", size, peer_addr); // First check if this is from an active stream (lock-free lookup) if let Some(handle) = active_streams.get(&peer_addr) { let _ = handle.input_tx.try_send(data); continue; } // Not an active stream, handle as potential new connection if let Err(e) = Self::handle_incoming_packet( data, &peer_addr, &conn_state, &connection_sender, max_pending, ).await { trace!( peer = %peer_addr, error = %e, "Failed to handle incoming packet" ); } } Err(e) => { error!(error = %e, "UDP receive failed"); break; } } } // Periodic cleanup _ = cleanup_interval.tick() => { Self::cleanup_dead_streams(&active_streams, &conn_state).await; Self::cleanup_pending_connections(&conn_state, handshake_timeout).await; } } } })); Ok(()) } ``` -------------------------------- ### Handling File Metadata Operations with and_then Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/error/type.Result.html?search=std%3A%3Avec Shows how to use `and_then` to chain fallible operations like getting file metadata and its modification time. This example highlights handling potential errors like file not found. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Get Error Cause (Deprecated) Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/error/enum.KcpError.html Provides a deprecated method for getting the cause of the error. The `Error::source` method is the modern replacement. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### Getting Value or Default with unwrap_or Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/error/type.Result.html?search= Demonstrates `unwrap_or` to get the `Ok` value or a provided default if the `Result` is `Err`. The default value is eagerly evaluated. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Convenience Connect and Listen Methods Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search=u32+-%3E+bool These methods provide a convenient way to establish KCP connections and listeners using Tokio's asynchronous runtime. ```APIDOC ## `connect` Method ### Description Establishes a KCP connection to a given address using the current configuration. ### Method `async fn connect>(self, addr: A) -> Result>` ### Parameters - `addr`: The address to connect to, which can be any type that can be converted into a `SocketAddr`. ### Returns A `Result` containing a `KcpStream` on success, or an error. ## `listen` Method ### Description Binds a KCP listener to a given address using the current configuration. ### Method `async fn listen>(self, addr: A) -> Result>` ### Parameters - `addr`: The address to bind the listener to, which can be any type that can be converted into a `SocketAddr`. ### Returns A `Result` containing a `KcpListener` on success, or an error. ``` -------------------------------- ### Get Error Description (Deprecated) Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/error/enum.KcpError.html Provides a deprecated method for getting a string description of the error. It is recommended to use the Display implementation or `to_string()` instead. ```rust fn description(&self) -> &str ``` -------------------------------- ### Getting a Mutable Reference with as_mut() Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/error/type.Result.html?search= Shows how to use `as_mut()` to get a `Result<&mut T, &mut E>` from a `&mut Result`. This enables in-place modification of the `Result`'s contained value. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### KcpConfig::new Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new KcpConfig with default settings. ```APIDOC ## KcpConfig::new ### Description Creates a new KcpConfig with default settings. ### Method `new()` ### Returns - `Self`: A new KcpConfig instance. ``` -------------------------------- ### KcpStream::stats Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/stream/struct.KcpStream.html?search= Get connection statistics for the KCP stream. ```APIDOC ## pub async fn stats(&self) -> KcpStats ### Description Get connection statistics. ### Method `async fn` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **KcpStats** - The connection statistics. #### Response Example None ``` -------------------------------- ### KcpStream::peer_addr Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/stream/struct.KcpStream.html?search= Get the peer address of the KCP stream. ```APIDOC ## pub fn peer_addr(&self) -> &T::Addr ### Description Get peer address. ### Method `fn` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **&T::Addr** - The peer address. #### Response Example None ``` -------------------------------- ### KcpConfig Connection Methods Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html Methods for establishing KCP connections, including client connection and server listening. ```rust pub async fn connect>( self, addr: A, ) -> Result> ``` ```rust pub async fn listen>( self, addr: A, ) -> Result> ``` -------------------------------- ### KcpStream::local_addr Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/stream/struct.KcpStream.html?search= Get the local address of the KCP stream. ```APIDOC ## pub fn local_addr(&self) -> Result ### Description Get local address. ### Method `fn` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **T::Addr** - The local address. #### Response Example None ``` -------------------------------- ### Testing Preset Configuration Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html Creates a KCP configuration suitable for testing, including fast mode and packet loss simulation. Requires a packet loss percentage as input. ```rust pub fn testing(packet_loss: f32) -> Self { Self::default() .fast_mode() .simulate_packet_loss(packet_loss) .connect_timeout(Duration::from_secs(5)) } ``` -------------------------------- ### KcpConfig Builder: New Instance Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html Creates a new KcpConfig instance with default values. Use this as the entry point for configuring KCP settings. ```rust pub fn new() -> Self { Self::default() } ``` -------------------------------- ### Realtime Preset Configuration Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html Creates a KCP configuration optimized for real-time applications. Uses fast mode with moderate window sizes, a standard MTU, and short timeouts/keep-alive. ```rust pub fn realtime() -> Self { Self::default() .fast_mode() .window_size(64, 64) .mtu(1200) .connect_timeout(Duration::from_secs(3)) .keep_alive(Some(Duration::from_secs(10))) } ``` -------------------------------- ### Get KcpSegment Size Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/protocol/struct.KcpSegment.html?search= Calculates and returns the total size of the KcpSegment in bytes. ```rust pub fn size(&self) -> usize ``` -------------------------------- ### Predefined KcpConfig Presets Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html?search= Offers convenient preset configurations for common use cases. Use `gaming()`, `file_transfer()`, `realtime()`, or `testing()` to quickly apply optimized settings. ```rust pub fn gaming() -> Self ``` ```rust pub fn file_transfer() -> Self ``` ```rust pub fn realtime() -> Self ``` ```rust pub fn testing(packet_loss: f32) -> Self ``` -------------------------------- ### KcpConfig Builder Methods Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html?search= Provides a fluent interface for configuring KcpConfig. Use these methods to set specific parameters like MTU, send/receive windows, delay configurations, and timeouts. ```rust pub fn new() -> Self ``` ```rust pub fn mtu(self, mtu: u32) -> Self ``` ```rust pub fn send_window(self, wnd: u32) -> Self ``` ```rust pub fn recv_window(self, wnd: u32) -> Self ``` ```rust pub fn window_size(self, snd_wnd: u32, rcv_wnd: u32) -> Self ``` ```rust pub fn normal_mode(self) -> Self ``` ```rust pub fn fast_mode(self) -> Self ``` ```rust pub fn turbo_mode(self) -> Self ``` ```rust pub fn nodelay_config(self, config: NodeDelayConfig) -> Self ``` ```rust pub fn max_retries(self, retries: u32) -> Self ``` ```rust pub fn stream_mode(self, enabled: bool) -> Self ``` ```rust pub fn connect_timeout(self, timeout: Duration) -> Self ``` ```rust pub fn keep_alive(self, interval: Option) -> Self ``` ```rust pub fn socket_buffer_size(self, size: usize) -> Self ``` ```rust pub fn simulate_packet_loss(self, loss_rate: f32) -> Self ``` -------------------------------- ### Get Local Address of KcpListener Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/listener/struct.KcpListener.html Retrieves the local network address that the KcpListener is bound to. ```rust pub fn local_addr(&self) -> &T::Addr ``` -------------------------------- ### Gaming Preset Configuration Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html Creates a KCP configuration optimized for gaming. Uses default settings with specific adjustments for nodelay, window size, MTU, connect timeout, and keep-alive. ```rust pub fn gaming() -> Self { Self::default() .nodelay_config(NodeDelayConfig::gaming()) .window_size(64, 128) .mtu(1200) .connect_timeout(Duration::from_secs(3)) .keep_alive(Some(Duration::from_secs(10))) } ``` -------------------------------- ### Get Peer Address of KCP Stream Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/stream.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns a reference to the peer address of the KCP stream. ```rust pub fn peer_addr(&self) -> &T::Addr { &self.peer_addr } ``` -------------------------------- ### KcpConfig Validation and Connection Methods Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html?search= Includes methods for validating the configuration and establishing connections or listeners. `validate` checks for valid settings, while `connect` and `listen` initiate network operations. ```rust pub fn validate(&self) -> Result<()> ``` ```rust pub async fn connect>( self, addr: A, ) -> Result> ``` ```rust pub async fn listen>( self, addr: A, ) -> Result> ``` -------------------------------- ### Preset Configurations Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search=u32+-%3E+bool Provides predefined `KcpConfig` instances tailored for different scenarios. ```APIDOC ## `gaming()` Preset ### Description Returns a `KcpConfig` optimized for gaming scenarios, with nodelay enabled and specific window sizes and timeouts. ### Returns A `KcpConfig` instance. ## `file_transfer()` Preset ### Description Returns a `KcpConfig` optimized for file transfer, prioritizing reliability with larger window sizes and longer timeouts. ### Returns A `KcpConfig` instance. ## `realtime()` Preset ### Description Returns a `KcpConfig` optimized for real-time applications, balancing speed and reliability. ### Returns A `KcpConfig` instance. ## `testing(packet_loss: f32)` Preset ### Description Returns a `KcpConfig` suitable for testing, allowing simulation of packet loss and with a configurable connection timeout. ### Parameters - `packet_loss`: A float representing the probability of packet loss (0.0 to 1.0). ### Returns A `KcpConfig` instance. ``` -------------------------------- ### Get Pending Connection Count Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/listener/struct.KcpListener.html Returns the current number of connections that are pending acceptance by the listener. ```rust pub async fn pending_count(&self) -> usize ``` -------------------------------- ### Gaming Preset Configuration Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search=std%3A%3Avec Provides a KcpConfig optimized for gaming, featuring low latency and quick response times. ```rust pub fn gaming() -> Self { Self::default() .nodelay_config(NodeDelayConfig::gaming()) .window_size(64, 128) .mtu(1200) .connect_timeout(Duration::from_secs(3)) .keep_alive(Some(Duration::from_secs(10))) } ``` -------------------------------- ### KcpStream::input_sender Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/stream.rs.html?search=std%3A%3Avec Gets a clone of the input sender channel. This is used internally for routing listener packets. ```APIDOC ## KcpStream::input_sender ### Description Provides a clone of the sender half of the channel used for receiving input data. This is primarily for internal use by listeners to route incoming packets to the correct stream. ### Method `fn input_sender(&self) -> mpsc::Sender` ### Parameters None ### Request Example ```rust // let sender = stream.input_sender(); ``` ### Response #### Success Response - `mpsc::Sender`: A sender for the input channel. #### Response Example ```rust // Sender { ... } ``` ``` -------------------------------- ### Get Local Address of KCP Stream Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/stream.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the local address of the transport associated with the KCP stream. ```rust pub fn local_addr(&self) -> Result { self.transport.local_addr().map_err(KcpError::Io) } ``` -------------------------------- ### KcpEngine::new Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html?search=std%3A%3Avec Creates a new KCP engine instance with a given conversation ID and configuration. ```APIDOC ## KcpEngine::new ### Description Create a new KCP engine. ### Method `new` ### Parameters - **conv** (u32) - The conversation ID for the engine. - **config** (impl Into) - The KCP configuration. ### Returns - KcpEngine - A new instance of the KcpEngine. ``` -------------------------------- ### Testing Preset Configuration Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search=std%3A%3Avec Provides a KcpConfig suitable for testing, allowing simulation of packet loss. ```rust pub fn testing(packet_loss: f32) -> Self { Self::default() .fast_mode() .simulate_packet_loss(packet_loss) .connect_timeout(Duration::from_secs(5)) } ``` -------------------------------- ### Get KcpStream Statistics Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/stream/struct.KcpStream.html?search= Asynchronously fetches the current KCP connection statistics. This can be useful for monitoring and debugging. ```rust pub async fn stats(&self) -> KcpStats ``` -------------------------------- ### KcpEngine::new Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html?search= Creates a new KCP engine instance with a specified conversation ID and configuration. ```APIDOC ## KcpEngine::new ### Description Creates a new KCP engine with a given conversation ID and configuration. ### Signature `pub fn new(conv: u32, config: impl Into) -> KcpEngine` ### Parameters * `conv` (u32) - The conversation ID for the KCP engine. * `config` (impl Into) - The configuration for the KCP core. ### Returns A new `KcpEngine` instance. ``` -------------------------------- ### Get Current Conversation ID Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html?search=u32+-%3E+bool Retrieves the current conversation ID (conv) associated with the KCP engine. ```rust pub fn conv(&self) -> u32 ``` -------------------------------- ### KcpConfig::connect Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Establishes a KCP connection to a given address. ```APIDOC ## KcpConfig::connect ### Description Establishes a KCP connection to a given address. ### Method `connect>(self, addr: A) -> Result>` ### Parameters - **addr** (A: Into) - The address to connect to. ### Returns - `Result>`: A KcpStream if the connection is successful, otherwise an Err. ``` -------------------------------- ### Get KCP Connection Statistics Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/stream.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Fetches the current statistics for the KCP connection. Returns default statistics if unavailable. ```rust pub async fn stats(&self) -> KcpStats { self.handle.stats().await.unwrap_or_default() } ``` -------------------------------- ### connect Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search= Establishes a KCP connection to a specified address using the current configuration. This is a convenience method for initiating a client-side connection. ```APIDOC ## connect ### Description Establishes a KCP connection to a specified address using the current configuration. This is a convenience method for initiating a client-side connection. ### Method `async fn connect>(self, addr: A) -> Result>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Assuming kcp_config is an instance of KcpConfig let stream = kcp_config.connect("127.0.0.1:1234").await?; ``` ### Response #### Success Response - `Result>`: A KcpStream ready for communication upon successful connection. ``` -------------------------------- ### Get Current Timestamp Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/protocol/fn.current_timestamp.html?search= Retrieves the current timestamp in milliseconds. This function returns a u32 value representing the time. ```rust pub fn current_timestamp() -> u32 ``` -------------------------------- ### Get KCP Statistics Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html?search=u32+-%3E+bool Retrieves the current statistics of the KCP engine, providing insights into performance and connection status. ```rust pub fn stats(&self) -> &KcpStats ``` -------------------------------- ### KcpConfig Blanket Implementations Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html?search=u32+-%3E+bool Demonstrates blanket implementations for traits like Any, Borrow, BorrowMut, CloneToUninit, From, Instrument, Into, and ToOwned. ```rust fn type_id(&self) -> TypeId ``` ```rust fn borrow(&self) -> &T ``` ```rust fn borrow_mut(&mut self) -> &mut T ``` ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` ```rust fn from(t: T) -> T ``` ```rust fn instrument(self, span: Span) -> Instrumented ``` ```rust fn in_current_span(self) -> Instrumented ``` ```rust fn into(self) -> U ``` ```rust type Owned = T ``` ```rust fn to_owned(&self) -> T ``` -------------------------------- ### KcpEngine Methods Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html Provides documentation for the public methods of the KcpEngine struct, detailing their functionality, parameters, and return types. ```APIDOC ## KcpEngine ### Description Synchronous KCP engine implementing the core protocol logic. All methods are synchronous. Output packets are buffered in `output_queue` and must be drained by the caller via `drain_output`. ### Methods #### `new(conv: u32, config: impl Into) -> KcpEngine` **Description:** Create a new KCP engine. #### `start(&mut self) -> Result<(), KcpCoreError>` **Description:** Start the engine. #### `conv(&self) -> u32` **Description:** Get the current conversation ID. #### `set_conv(&mut self, conv: u32)` **Description:** Override the conversation ID. Used by the server-side handshake where the listener allocates a new non-zero `conv` after a client connects with `conv=0` (the tokio_kcp handshake convention). All subsequent outgoing segments will carry the new `conv`. #### `drain_output(&mut self) -> Vec` **Description:** Drain buffered output packets. The caller is responsible for sending each `Bytes` over the transport. #### `send(&mut self, data: Bytes) -> Result<(), KcpCoreError>` **Description:** Send data through KCP. #### `recv(&mut self) -> Result, KcpCoreError>` **Description:** Receive data from KCP. #### `input(&mut self, data: Bytes) -> Result<(), KcpCoreError>` **Description:** Process incoming packet. #### `flush(&mut self) -> Result<(), KcpCoreError>` **Description:** Flush pending data and ACKs. #### `update(&mut self) -> Result<(), KcpCoreError>` **Description:** Update KCP state (called periodically). #### `stats(&self) -> &KcpStats` **Description:** Get current statistics. #### `is_dead(&self) -> bool` **Description:** Check if connection is alive. #### `idle_ms(&self) -> u32` **Description:** Milliseconds since last send or receive activity. #### `keep_alive_probe(&mut self) -> Result<(), KcpCoreError>` **Description:** Trigger a window probe to keep the connection alive. ``` -------------------------------- ### Try Get a Buffer from the Pool Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/buffer_pool/struct.BufferPool.html?search= Attempts to retrieve a buffer from the pool in a lock-free manner. Returns a BytesMut if successful. ```rust pub fn try_get(&self) -> BytesMut ``` -------------------------------- ### Get Current Metrics Snapshot Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/metrics/struct.GlobalMetrics.html Retrieves a snapshot of the current global performance metrics. The snapshot is returned as a MetricsSnapshot object. ```rust pub fn snapshot(&self) -> MetricsSnapshot ``` -------------------------------- ### connect Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Establishes a KCP connection to a specified address using the current configuration. This method is available when the `tokio` feature is enabled. ```APIDOC ## connect ### Description Asynchronously connects to a remote endpoint using the KCP protocol with the configured parameters. This is a convenience method that wraps the underlying stream and transport setup. ### Method `async fn connect>(self, addr: A) -> Result>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Assuming kcp_config is a KcpConfig instance let stream = kcp_config.connect("127.0.0.1:1234").await?; ``` ### Response #### Success Response - `Result>`: On success, returns a `KcpStream` ready for communication. #### Response Example ```rust // Success case returns a KcpStream Ok(kcp_stream) ``` #### Error Response - `Result<...>`: On failure, returns an error. ``` ``` -------------------------------- ### Get Input Sender Channel Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/stream.rs.html Provides a clone of the input sender channel, useful for routing packets from a listener to the KCP stream. ```rust pub(crate) fn input_sender(&self) -> mpsc::Sender { self.input_tx.clone() } ``` -------------------------------- ### Get Local Address of KcpStream Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/stream/struct.KcpStream.html?search= Retrieves the local address associated with the KCP stream. The address type depends on the underlying Transport. ```rust pub fn local_addr(&self) -> Result ``` -------------------------------- ### listen Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search= Binds a KCP listener to a specified address using the current configuration. This is a convenience method for setting up a server-side listener. ```APIDOC ## listen ### Description Binds a KCP listener to a specified address using the current configuration. This is a convenience method for setting up a server-side listener. ### Method `async fn listen>(self, addr: A) -> Result>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Assuming kcp_config is an instance of KcpConfig let listener = kcp_config.listen("0.0.0.0:1234").await?; ``` ### Response #### Success Response - `Result>`: A KcpListener ready to accept incoming connections upon successful binding. ``` -------------------------------- ### KcpConfig Builder: Transport and Runtime Tuning Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search=std%3A%3Avec Offers builder methods for transport-level and runtime settings, including connection timeouts, keep-alive intervals, and socket buffer sizes. These options allow fine-tuning of the network transport layer for KCP. ```rust pub fn connect_timeout(mut self, timeout: Duration) -> Self { self.connect_timeout = timeout; self } pub fn keep_alive(mut self, interval: Option) -> Self { self.keep_alive = interval; self } pub fn socket_buffer_size(mut self, size: usize) -> Self { self.socket_buffer_size = Some(size); self } pub fn simulate_packet_loss(mut self, loss_rate: f32) -> Self { if (0.0..=1.0).contains(&loss_rate) { self.simulate_packet_loss = Some(loss_rate); } self } ``` -------------------------------- ### File Transfer Preset Configuration Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html Creates a KCP configuration optimized for file transfers. Uses normal mode with larger window sizes, a higher MTU, stream mode enabled, and longer timeouts/keep-alive. ```rust pub fn file_transfer() -> Self { Self::default() .normal_mode() .window_size(256, 256) .mtu(1400) .stream_mode(true) .connect_timeout(Duration::from_secs(30)) .keep_alive(Some(Duration::from_secs(60))) } ``` -------------------------------- ### Get Local Address of KCP Listener Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/listener.rs.html?search= Retrieves the local network address the KCP listener is bound to. This is useful for configuration or informational purposes. ```rust pub fn local_addr(&self) -> &T::Addr { &self.local_addr } ``` -------------------------------- ### KcpConfig Validation and Connection Methods Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html?search=u32+-%3E+bool Includes methods for validating the current configuration and for establishing KCP connections or listeners. ```APIDOC ## KcpConfig Validation and Connection Methods ### `validate(&self) -> Result<()>` Validates the current KCP configuration. Returns `Ok(())` if valid, or an error if not. ### `connect>(self, addr: A) -> Result>` Asynchronously connects to a remote address using the current KCP configuration. Returns a `KcpStream` on success. ### `listen>(self, addr: A) -> Result>` Asynchronously creates a KCP listener bound to the specified address using the current configuration. Returns a `KcpListener` on success. ``` -------------------------------- ### Get Peer Address of KcpStream Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/stream/struct.KcpStream.html?search= Returns a reference to the peer's address for the KCP stream. The address type is determined by the Transport implementation. ```rust pub fn peer_addr(&self) -> &T::Addr ``` -------------------------------- ### Get Local Address Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/transport/struct.UdpTransport.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the local socket address that this transport is bound to. This is useful for determining the network interface and port the transport is using. ```rust fn local_addr(&self) -> Result ``` -------------------------------- ### KcpConfig Builder: Protocol Tuning Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search=std%3A%3Avec Provides builder methods for configuring KCP protocol parameters such as MTU, send/receive window sizes, and nodelay modes. These methods allow for fluent and readable configuration of the KCP protocol settings. ```rust pub fn mtu(mut self, mtu: u32) -> Self { self.mtu = mtu; self } pub fn send_window(mut self, wnd: u32) -> Self { self.snd_wnd = wnd; self } pub fn recv_window(mut self, wnd: u32) -> Self { self.rcv_wnd = wnd; self } pub fn window_size(mut self, snd_wnd: u32, rcv_wnd: u32) -> Self { self.snd_wnd = snd_wnd; self.rcv_wnd = rcv_wnd; self } pub fn normal_mode(mut self) -> Self { self.nodelay = NodeDelayConfig::normal(); self } pub fn fast_mode(mut self) -> Self { self.nodelay = NodeDelayConfig::fast(); self } pub fn turbo_mode(mut self) -> Self { self.nodelay = NodeDelayConfig::turbo(); self } pub fn nodelay_config(mut self, config: NodeDelayConfig) -> Self { self.nodelay = config; self } pub fn max_retries(mut self, retries: u32) -> Self { self.max_retries = retries; self } pub fn stream_mode(mut self, enabled: bool) -> Self { self.stream_mode = enabled; self } ``` -------------------------------- ### Get Milliseconds Since Last Activity Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/engine/struct.KcpEngine.html?search=u32+-%3E+bool Calculates the time in milliseconds that has passed since the last send or receive activity on the KCP connection. ```rust pub fn idle_ms(&self) -> u32 ``` -------------------------------- ### KcpConfig Builder Methods Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html?search=u32+-%3E+bool Provides a fluent interface for configuring KcpConfig. Methods allow setting individual parameters like MTU, send/receive windows, delay configurations, retry limits, stream mode, timeouts, socket buffer size, and packet loss simulation. ```APIDOC ## KcpConfig Builder Methods ### `new()` Creates a new KcpConfig with default values. ### `mtu(self, mtu: u32) -> Self` Sets the Maximum Transmission Unit (MTU). ### `send_window(self, wnd: u32) -> Self` Sets the send window size. ### `recv_window(self, wnd: u32) -> Self` Sets the receive window size. ### `window_size(self, snd_wnd: u32, rcv_wnd: u32) -> Self` Sets both send and receive window sizes. ### `normal_mode(self) -> Self` Configures KCP for normal operation mode. ### `fast_mode(self) -> Self` Configures KCP for fast operation mode. ### `turbo_mode(self) -> Self` Configures KCP for turbo operation mode. ### `nodelay_config(self, config: NodeDelayConfig) -> Self` Sets the no-delay configuration. ### `max_retries(self, retries: u32) -> Self` Sets the maximum number of retries. ### `stream_mode(self, enabled: bool) -> Self` Enables or disables stream mode. ### `connect_timeout(self, timeout: Duration) -> Self` Sets the connection timeout duration. ### `keep_alive(self, interval: Option) -> Self` Configures the keep-alive interval. ### `socket_buffer_size(self, size: usize) -> Self` Sets the size of the socket buffer. ### `simulate_packet_loss(self, loss_rate: f32) -> Self` Configures packet loss simulation rate. ``` -------------------------------- ### KcpConfig::listen Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/config/struct.KcpConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a KCP listener bound to a given address. ```APIDOC ## KcpConfig::listen ### Description Creates a KCP listener bound to a given address. ### Method `listen>(self, addr: A) -> Result>` ### Parameters - **addr** (A: Into) - The address to bind the listener to. ### Returns - `Result>`: A KcpListener if successful, otherwise an Err. ``` -------------------------------- ### Process Engine Commands in Actor Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/actor.rs.html?search=u32+-%3E+bool Handles various commands sent to the KCP engine, such as flushing, getting stats, checking liveness, and graceful shutdown. ```Rust match cmd { Some(EngineCmd::Flush { reply }) => { let r = engine.flush().map_err(KcpError::from); flush_output(&mut engine, &transport, &peer_addr).await; let _ = reply.send(r); } Some(EngineCmd::Stats { reply }) => { let _ = reply.send(*engine.stats()); } Some(EngineCmd::IsAlive { reply }) => { let _ = reply.send(!engine.is_dead()); } Some(EngineCmd::Close) | None => { // Graceful shutdown: flush remaining data let _ = engine.flush(); flush_output(&mut engine, &transport, &peer_addr).await; break; } Some(EngineCmd::NewPacket { .. }) => unreachable!(), } ``` -------------------------------- ### KcpConfig Presets Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/config.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides preset `KcpConfig` instances optimized for different network scenarios. ```APIDOC ## KcpConfig Presets ### Description These methods provide pre-configured `KcpConfig` instances suitable for common use cases, allowing for quick setup without manual parameter tuning. ### Methods #### `gaming()` Optimized for low latency gaming scenarios. #### `file_transfer()` Optimized for reliable and high-throughput file transfers. #### `realtime()` Optimized for real-time applications like voice or video communication. #### `testing(packet_loss: f32)` Configured for testing purposes, with an option to simulate packet loss. ### Usage Example ```rust // Use the gaming preset let config = KcpConfig::gaming(); // Use the file transfer preset let config = KcpConfig::file_transfer(); // Use the realtime preset let config = KcpConfig::realtime(); // Use the testing preset with 10% packet loss let config = KcpConfig::testing(0.1); ``` ### Response Each method returns a `KcpConfig` instance tailored for its specific purpose. ``` -------------------------------- ### try_get_buffer Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/buffer_pool/fn.try_get_buffer.html?search=std%3A%3Avec Gets a buffer from the global pool in a non-blocking manner. This function is useful for scenarios where immediate buffer allocation is required without waiting for availability. ```APIDOC ## Function try_get_buffer ### Description Get a buffer from the global pool (non-blocking). ### Signature ```rust pub fn try_get_buffer(size_hint: usize) -> BytesMut ``` ### Parameters * `size_hint` (usize) - A hint for the desired buffer size. ``` -------------------------------- ### Create a New BufferPool Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/buffer_pool/struct.BufferPool.html?search= Initializes a new BufferPool with a specified maximum size and buffer size. This is the constructor for the BufferPool. ```rust pub fn new(max_size: usize, buffer_size: usize) -> Self ``` -------------------------------- ### Get Buffer Pool Statistics Source: https://docs.rs/kcp-tokio/latest/kcp_tokio/buffer_pool/fn.buffer_pool_stats.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves statistics for the buffer pool. This function is useful for monitoring the allocation and usage of buffers within the kcp-tokio system. ```rust pub fn buffer_pool_stats() -> Vec<(&'static str, usize, usize)> ``` -------------------------------- ### KcpConfig Source: https://docs.rs/kcp-tokio/latest/index.html Configuration options for setting up KCP connections. ```APIDOC ## KcpConfig ### Description Provides methods to configure KCP connection parameters. ### Methods - `new()`: Creates a new `KcpConfig` with default settings. - `fast_mode()`: Enables fast mode for the KCP configuration. ### Parameters None directly for `KcpConfig` itself, but methods modify its internal state. ### Request Example ```rust use kcp_tokio::KcpConfig; let config = KcpConfig::new().fast_mode(); ``` ### Response #### Success Response (KcpConfig) Returns a configured `KcpConfig` object. #### Response Example ```rust // A KcpConfig object ``` ``` -------------------------------- ### Get KCP Stream Input Sender Source: https://docs.rs/kcp-tokio/latest/src/kcp_tokio/stream.rs.html?search= Provides a clone of the input sender channel for routing incoming packets to the KCP engine. This is typically used by a listener. ```rust pub(crate) fn input_sender(&self) -> mpsc::Sender { self.input_tx.clone() } ```