pub trait WebSocketHandler: Send + Sync {
// Required method
fn handle_message(
&self,
message: Value,
) -> impl Future<Output = Option<Value>> + Send;
// Provided methods
fn on_connect(&self) -> impl Future<Output = ()> + Send { ... }
fn on_disconnect(&self) -> impl Future<Output = ()> + Send { ... }
}Expand description
WebSocket message handler trait
Implement this trait to create custom WebSocket message handlers for your application. The handler processes JSON messages received from WebSocket clients and can optionally send responses back.
§Implementing the Trait
You must implement the handle_message method. The on_connect and on_disconnect
methods are optional and provide lifecycle hooks.
§Example
use spikard_http::websocket::WebSocketHandler;
use serde_json::{json, Value};
struct EchoHandler;
#[async_trait]
impl WebSocketHandler for EchoHandler {
async fn handle_message(&self, message: Value) -> Option<Value> {
// Echo the message back to the client
Some(message)
}
async fn on_connect(&self) {
println!("Client connected");
}
async fn on_disconnect(&self) {
println!("Client disconnected");
}
}Required Methods§
Provided Methods§
Sourcefn on_connect(&self) -> impl Future<Output = ()> + Send
fn on_connect(&self) -> impl Future<Output = ()> + Send
Called when a client connects to the WebSocket
Optional lifecycle hook invoked when a new WebSocket connection is established. Default implementation does nothing.
Sourcefn on_disconnect(&self) -> impl Future<Output = ()> + Send
fn on_disconnect(&self) -> impl Future<Output = ()> + Send
Called when a client disconnects from the WebSocket
Optional lifecycle hook invoked when a WebSocket connection is closed (either by the client or due to an error). Default implementation does nothing.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.