Skip to main content

WebSocketHandler

Trait WebSocketHandler 

Source
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§

Source

fn handle_message( &self, message: Value, ) -> impl Future<Output = Option<Value>> + Send

Handle incoming WebSocket message

Called whenever a text message is received from a WebSocket client. Messages are automatically parsed as JSON.

§Arguments
  • message - JSON value received from the client
§Returns
  • Some(value) - JSON value to send back to the client
  • None - No response to send

Provided Methods§

Source

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.

Source

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.

Implementors§