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

69 lines
2.4 KiB
Rust

//! Basic WSS (WebSocket Secure) server example
//!
//! This example demonstrates how to start a WSS server with TLS enabled.
//! It uses the existing certificate and key files for testing.
//!
//! To run this example:
//! ```bash
//! cargo run --example wss_basic_example
//! ```
use circle_ws_lib::{spawn_circle_server, ServerConfig};
use log::info;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize logging
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
info!("🚀 Starting Basic WSS Server Example");
// Create server configuration with TLS enabled
let config = ServerConfig::new(
"127.0.0.1".to_string(),
8443, // Use port 8443 for WSS
"redis://127.0.0.1/".to_string(),
)
.with_tls("cert.pem".to_string(), "key.pem".to_string())
.with_tls_port(8443);
info!("📋 Server Configuration:");
info!(" Host: {}", config.host);
info!(" WSS Port: {}", config.get_tls_port());
info!(" TLS Enabled: {}", config.enable_tls);
info!(" Auth Enabled: {}", config.enable_auth);
info!(" Certificate: {:?}", config.cert_path);
info!(" Private Key: {:?}", config.key_path);
// Start the WSS server
let (server_task, server_handle) = spawn_circle_server(config)?;
info!("✅ WSS Server started successfully!");
info!("🔒 You can now connect to: wss://127.0.0.1:8443/ws");
info!("📝 Note: This uses a self-signed certificate for testing");
info!("");
info!("🧪 To test the connection, you can use:");
info!(" - A WebSocket client that supports WSS");
info!(" - The client_ws library with TLS support");
info!(" - Browser developer tools (may show certificate warnings)");
info!("");
info!("⏰ Server will run for 30 seconds, then shutdown...");
// Let the server run for 30 seconds
sleep(Duration::from_secs(30)).await;
info!("🛑 Shutting down WSS server...");
server_handle.stop(true).await;
// Wait for the server task to complete
match server_task.await {
Ok(Ok(())) => info!("✅ WSS server shut down successfully"),
Ok(Err(e)) => info!("⚠️ WSS server shut down with error: {}", e),
Err(e) => info!("❌ Failed to wait for server shutdown: {}", e),
}
info!("🏁 Basic WSS example completed");
Ok(())
}