Socket.IO Controllers
In Sword, a Socket.IO controller is a struct annotated with #[controller(kind = Controller::SocketIo, namespace = "...")], and its methods handle events declared with #[on("...")].
Define a controller
rust
use sword::prelude::*;
use sword::socketio::*;
#[controller(kind = Controller::SocketIo, namespace = "/chat")]
pub struct ChatController;
impl ChatController {
#[on("connection")]
async fn on_connect(&self, ctx: SocketContext) {
println!("Client connected: {}", ctx.id());
}
#[on("message")]
async fn on_message(&self, ctx: SocketContext) {
let Ok(message) = ctx.try_data::<String>() else {
return;
};
ctx.socket.emit("message", &message).ok();
}
}Supported events
Special events
#[on("connection")]#[on("disconnection")]#[on("fallback")]
Custom events
#[on("message")]#[on("chat-message")]#[on("room:join")]
Register in a module
rust
use sword::prelude::*;
pub struct ChatModule;
impl Module for ChatModule {
fn register_controllers(controllers: &ControllerRegistry) {
controllers.register::<ChatController>();
}
}
