# Circle WebSocket Client (`circle_client_ws`) This crate provides a WebSocket client (`CircleWsClient`) designed to interact with a server that expects JSON-RPC messages, specifically for executing Rhai scripts. It is designed to be compatible with both WebAssembly (WASM) environments (e.g., web browsers) and native Rust applications. ## Features - **Cross-Platform:** Works in WASM and native environments. - Uses `gloo-net` for WebSockets in WASM. - Uses `tokio-tungstenite` for WebSockets in native applications. - **JSON-RPC Communication:** Implements client-side JSON-RPC 2.0 request and response handling. - **Rhai Script Execution:** Provides a `play(script: String)` method to send Rhai scripts to the server for execution and receive their output. - **Asynchronous Operations:** Leverages `async/await` and `futures` for non-blocking communication. - **Connection Management:** Supports connecting to and disconnecting from a WebSocket server. - **Error Handling:** Defines a comprehensive `CircleWsClientError` enum for various client-side errors. ## Core Component - **`CircleWsClient`**: The main client struct. - `new(ws_url: String)`: Creates a new client instance targeting the given WebSocket URL. - `connect()`: Establishes the WebSocket connection. - `play(script: String)`: Sends a Rhai script to the server for execution and returns the result. - `disconnect()`: Closes the WebSocket connection. ## Usage Example (Conceptual) ```rust use circle_client_ws::CircleWsClient; async fn run_client() { let mut client = CircleWsClient::new("ws://localhost:8080/ws".to_string()); if let Err(e) = client.connect().await { eprintln!("Failed to connect: {}", e); return; } let script = "print(\"Hello from Rhai via WebSocket!\"); 40 + 2".to_string(); match client.play(script).await { Ok(result) => { println!("Script output: {}", result.output); } Err(e) => { eprintln!("Error during play: {}", e); } } client.disconnect().await; } // To run this example, you'd need an async runtime like tokio for native // or wasm-bindgen-test for WASM. ``` ## Building ### Native ```bash cargo build ``` ### WASM ```bash cargo build --target wasm32-unknown-unknown ``` ## Dependencies Key dependencies include: - `serde`, `serde_json`: For JSON serialization/deserialization. - `futures-channel`, `futures-util`: For asynchronous stream and sink handling. - `uuid`: For generating unique request IDs. - `log`: For logging. - `thiserror`: For error type definitions. **WASM-specific:** - `gloo-net`: For WebSocket communication in WASM. - `wasm-bindgen-futures`: To bridge Rust futures with JavaScript promises. **Native-specific:** - `tokio-tungstenite`: For WebSocket communication in native environments. - `tokio`: Asynchronous runtime for native applications. - `url`: For URL parsing.