Real-World Code Blueprints100% Rust Safe Core

Interactive Examples Hub

Don't just read documentation. Inspect production-ready Rust code blocks and message flows for Echo, Encrypted Chat, High-Speed Streaming, File Transfers, REST over KSP, and Edge Gateway translation.

Stream ID: 1 (Bidirectional)

1. Minimal Echo Server

The 'Hello World' of KSP. Opens TCP socket `9876`, performs X25519 key exchange, and mirrors decrypted payload frames back to the sender.

Simulated Wire Message Flow
[Client] -> StreamOpen (Stream ID: 1)
[Server] -> StreamOpenAck (Stream ID: 1)
[Client] -> StreamData payload="Hello KSP from Rust!"
[Server] -> StreamData payload="Hello KSP from Rust!" (mirrored exactly)
[Client] -> GoAway (graceful termination)
examples/echo_server.rs
// examples/echo_server.rs
use ksp::{KspServer, SessionConfig, PacketType};
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = TcpListener::bind("0.0.0.0:9876").await?;
    println!("[KSP] Echo server listening on 9876/tcp...");

    while let Ok((socket, addr)) = listener.accept().await {
        tokio::spawn(async move {
            let mut session = KspServer::accept(socket, SessionConfig::default()).await.unwrap();
            
            while let Ok(frame) = session.recv_frame().await {
                match frame.header.packet_type {
                    PacketType::StreamData => {
                        println!("[Stream {}] Echoing {} bytes", frame.header.stream_id, frame.payload.len());
                        session.send_data(frame.header.stream_id, &frame.payload).await.unwrap();
                    }
                    PacketType::GoAway => break,
                    _ => {}
                }
            }
        });
    }
    Ok(())
}