Complete reference for all public APIs in the WsForge WebSocket framework.
- Core Types
- Router
- Connection & ConnectionManager
- Message & MessageType
- Handlers
- Extractors
- State Management
- Error Types
- Static Files
- Macros
Type alias for std::result::Result<T, Error>.
pub type Result<T> = std::result::Result<T, Error>;
Type alias for connection identifiers.
pub type ConnectionId = String;
The main entry point for building WebSocket servers.
Creates a new empty router.
let router = Router::new();
Registers a handler for a specific route pattern.
Parameters:
path- Route path (e.g., "/chat", "/api")handler- Handler wrapped withhandler()
Example:
async fn chat_handler(msg: Message) -> Result<String> {
Ok("chat response".to_string())
}
let router = Router::new()
.route("/chat", handler(chat_handler));
Adds shared application state.
Parameters:
data- State data (must beSend + Sync + 'static)
Example:
struct Database { /* ... */ }
let router = Router::new()
.with_state(Arc::new(Database::new()));
Sets the default handler for messages that don't match any route.
Example:
let router = Router::new()
.default_handler(handler(my_handler));
Enables static file serving from a directory.
Parameters:
path- Directory path containing static files
Example:
let router = Router::new()
.serve_static("public");
Sets callback for when connections are established.
Signature:
where F: Fn(&Arc<ConnectionManager>, ConnectionId) + Send + Sync + 'static
Example:
let router = Router::new()
.on_connect(|manager, conn_id| {
println!("Connected: {}", conn_id);
});
Sets callback for when connections are closed.
Example:
let router = Router::new()
.on_disconnect(|manager, conn_id| {
println!("Disconnected: {}", conn_id);
});
Returns a reference to the connection manager.
Example:
let manager = router.connection_manager();
println!("Active: {}", manager.count());
Starts the WebSocket server (async).
Parameters:
addr- Bind address (e.g., "127.0.0.1:8080")
Example:
router.listen("0.0.0.0:8080").await?;
Represents an active WebSocket connection.
Creates a new connection (typically internal use).
Sends a message to the client.
Example:
conn.send(Message::text("Hello!"))?;
Sends a text message.
Example:
conn.send_text("Hello, client!")?;
Sends binary data.
Example:
conn.send_binary(vec![0x01, 0x02, 0x03])?;
Serializes and sends JSON data.
Example:
#[derive(Serialize)]
struct Response { status: String }
conn.send_json(&Response { status: "ok".to_string() })?;
Returns the connection ID.
Returns connection metadata.
Manages all active connections.
Creates a new connection manager.
Adds a connection and returns total count.
Removes a connection by ID.
Retrieves a connection by ID.
Example:
if let Some(conn) = manager.get(&conn_id) {
conn.send_text("message")?;
}
Broadcasts message to all connections.
Example:
manager.broadcast(Message::text("Announcement!"));
Broadcasts to all except one connection.
Example:
manager.broadcast_except(&sender_id, msg);
Broadcasts to specific connections.
Example:
let room_members = vec!["conn_1".to_string(), "conn_2".to_string()];
manager.broadcast_to(&room_members, msg);
Returns the number of active connections.
Returns all connection IDs.
Returns clones of all connections.
WebSocket message type.
Creates a text message.
let msg = Message::text("Hello");
Creates a binary message.
let msg = Message::binary(vec!);[11][12]
Creates a ping frame.
Creates a pong frame.
Creates a close frame.
Checks if message is text.
Checks if message is binary.
Checks if message is close frame.
Returns text content if text message.
if let Some(text) = msg.as_text() {
println!("Text: {}", text);
}
Returns raw bytes (works for all types).
Deserializes message as JSON.
#[derive(Deserialize)]
struct Data { name: String }
let data: Data = msg.json()?;
Message type enum.
pub enum MessageType {
Text,
Binary,
Ping,
Pong,
Close,
}
Converts an async function into a handler.
Example:
async fn my_handler(msg: Message) -> Result<String> {
Ok("response".to_string())
}
let h = handler(my_handler);
#[async_trait]
pub trait Handler: Send + Sync + 'static {
async fn call(
&self,
message: Message,
conn: Connection,
state: AppState,
extensions: Extensions,
) -> Result<Option<Message>>;
}
Types that can be returned from handlers.
Implementations:
()- No responseString- Text message&str- Text messageMessage- Raw messageVec<u8>- Binary messageJsonResponse<T>- JSON responseResult<T>- Automatic error handling
Wrapper for JSON responses.
#[derive(Serialize)]
struct Response { status: String }
async fn handler() -> Result<JsonResponse<Response>> {
Ok(JsonResponse(Response { status: "ok".to_string() }))
}
Extracts and deserializes JSON from messages.
#[derive(Deserialize)]
struct Request { name: String }
async fn handler(Json(req): Json<Request>) -> Result<String> {
Ok(format!("Hello, {}", req.name))
}
Extracts shared application state.
async fn handler(State(db): State<Arc<Database>>) -> Result<String> {
// Use database
Ok("result".to_string())
}
Extracts the active connection.
async fn handler(conn: Connection) -> Result<()> {
println!("From: {}", conn.id());
Ok(())
}
Extracts connection metadata.
async fn handler(ConnectInfo(info): ConnectInfo) -> Result<String> {
Ok(format!("Connected from: {}", info.addr))
}
Extracts raw binary data.
async fn handler(Data(bytes): Data) -> Result<String> {
Ok(format!("Received {} bytes", bytes.len()))
}
Extracts the raw message.
async fn handler(msg: Message) -> Result<Message> {
Ok(msg)
}
Type-safe container for shared state.
Creates empty state.
Inserts state data.
let state = AppState::new();
state.insert(Arc::new(Database::new()));
Retrieves state data.
if let Some(db) = state.get::<Database>() {
// Use database
}
Request-scoped data container.
Creates empty extensions.
Inserts extension data.
extensions.insert("user_id", 123_u64);
Retrieves extension data.
Main error enum.
pub enum Error {
WebSocket(tokio_tungstenite::tungstenite::Error),
Io(std::io::Error),
Json(serde_json::Error),
ConnectionNotFound(String),
RouteNotFound(String),
InvalidMessage,
Handler(String),
Extractor(String),
Custom(String),
}
Creates custom error.
return Err(Error::custom("Something went wrong"));
Creates handler error.
Creates extractor error.
Serves static files.
Creates handler for directory.
let handler = StaticFileHandler::new("public");
Serves a file (returns content and MIME type).
Attribute macro for handler functions.
#[websocket_handler]
async fn my_handler(msg: Message) -> Result<String> {
Ok("response".to_string())
}
Derives message conversion methods.
#[derive(WebSocketMessage, Serialize, Deserialize)]
struct ChatMsg {
text: String,
}
Derives Handler trait implementation.
#[derive(WebSocketHandler)]
struct MyHandler;
// Handler signatures
async fn handler1() -> Result<String>
async fn handler2(msg: Message) -> Result<Message>
async fn handler3(Json(data): Json<T>) -> Result<JsonResponse<R>>
async fn handler4(msg: Message, conn: Connection) -> Result<()>
async fn handler5(State(s): State<Arc<T>>) -> Result<String>
// Multiple extractors
async fn handler6(
Json(data): Json<Request>,
conn: Connection,
State(manager): State<Arc<ConnectionManager>>,
) -> Result<JsonResponse<Response>>
Current Version: 0.1.0 Minimum Rust Version: 1.70 Documentation: https://docs.rs/wsforge Repository: https://github.com/aarambhdevhub/wsforge