circles/examples/wss_demo/wss_client.rs
2025-07-08 22:49:47 +02:00

94 lines
3.8 KiB
Rust

//! WSS Client Demo using Circle WebSocket Client
//!
//! This example demonstrates connecting to a WSS (WebSocket Secure) server
//! using the circle_client_ws library with proper authentication.
use circle_client_ws::{CircleWsClientBuilder, auth};
use log::{info, error};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize logging - use RUST_LOG=info for detailed output
env_logger::init();
println!("🧪 Starting WSS Client Demo");
// Generate authentication credentials
let private_key = auth::generate_private_key()?;
let public_key = auth::derive_public_key(&private_key)?;
info!("🔑 Generated credentials - Public key: {}...", &public_key[..20]);
// WSS server URL (secure WebSocket)
let wss_url = "wss://127.0.0.1:8443/ws";
info!("🔗 Connecting to WSS server at {}", wss_url);
println!("🔌 Connecting to WSS server...");
// Create WSS client with authentication
let mut client = CircleWsClientBuilder::new(wss_url.to_string())
.with_keypair(private_key)
.build();
// Connect to the server
match client.connect().await {
Ok(()) => {
println!("✅ Successfully connected to WSS server!");
info!("📡 Response status: 101 Switching Protocols");
println!("\n🧪 Testing WSS connection with JSON-RPC messages...");
// Test 1: Authentication
println!("📤 Test 1: Performing authentication");
match client.authenticate().await {
Ok(true) => {
println!("✅ Authentication successful!");
info!("🔐 Client authenticated with server");
// Test 2: Execute script (authenticated request)
println!("\n📤 Test 2: Executing script (authenticated request)");
let test_script = "40 + 2".to_string();
match client.play(test_script).await {
Ok(result) => {
println!("✅ Script execution successful!");
println!("📊 Result: {}", result.output);
info!("Script output: {}", result.output);
}
Err(e) => {
error!("❌ Script execution failed: {}", e);
println!("❌ Script execution failed: {}", e);
}
}
}
Ok(false) => {
println!("❌ Authentication failed - server rejected credentials");
error!("Authentication failed");
}
Err(e) => {
error!("❌ Authentication error: {}", e);
println!("❌ Authentication error: {}", e);
}
}
// Disconnect
client.disconnect().await;
println!("\n🔌 Disconnected from WSS server");
println!("\n🎉 Summary:");
println!(" ✅ WSS connection established");
println!(" ✅ TLS encryption working");
println!(" ✅ JSON-RPC protocol working");
println!(" ✅ Authentication system working");
println!(" ✅ Script execution working");
}
Err(e) => {
error!("❌ Failed to connect to WSS server: {}", e);
println!("❌ Connection failed: {}", e);
println!("\n💡 Make sure the WSS server is running:");
println!(" cargo run --manifest-path src/server/Cargo.toml --example wss_server --features auth");
}
}
Ok(())
}