Build real-time applications with ease and exceptional performance
- ๐ High Performance - Built on tokio-tungstenite with zero-copy optimizations
- ๐ง Type-Safe Extractors - Automatic JSON, State, and Connection extraction
- ๐ฏ Flexible Handlers - Return String, Message, Result, JsonResponse, or ()
- ๐ก Broadcasting - Built-in broadcast, broadcast_except, and targeted messaging
- โก Concurrent - Lock-free connection management using DashMap
- ๐ Lifecycle Hooks - on_connect and on_disconnect callbacks
- ๐ Hybrid Server - Serve static files and WebSocket on the same port
- ๐ก๏ธ Type Safety - Compile-time guarantees prevent common errors
- ๐จ Developer Friendly - Intuitive API inspired by Axum
- ๐ฆ Batteries Included - Macros, examples, and comprehensive documentation
Add WsForge to your Cargo.toml:
[dependencies]
wsforge = "0.1.0"
tokio = { version = "1.40", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
use wsforge::prelude::*;
async fn echo(msg: Message) -> Result<Message> {
Ok(msg)
}
#[tokio::main]
async fn main() -> Result<()> {
let router = Router::new()
.default_handler(handler(echo));
println!("๐ WebSocket server running on ws://127.0.0.1:8080");
router.listen("127.0.0.1:8080").await?;
Ok(())
}use wsforge::prelude::*;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct ChatMessage {
username: String,
text: String,
}
async fn chat_handler(
Json(msg): Json<ChatMessage>,
conn: Connection,
State(manager): State<Arc<ConnectionManager>>,
) -> Result<()> {
println!("{}: {}", msg.username, msg.text);
// Broadcast to everyone except sender
let response = serde_json::to_string(&msg)?;
manager.broadcast_except(conn.id(), Message::text(response));
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
let router = Router::new()
.default_handler(handler(chat_handler))
.on_connect(|manager, conn_id| {
println!("โ
{} joined (Total: {})", conn_id, manager.count());
})
.on_disconnect(|manager, conn_id| {
println!("โ {} left (Total: {})", conn_id, manager.count());
});
router.listen("127.0.0.1:8080").await?;
Ok(())
}wsforge/
โโโ wsforge-core/ # Core framework implementation
โ โโโ src/
โ โ โโโ connection.rs # Connection management
โ โ โโโ message.rs # Message types
โ โ โโโ handler.rs # Handler traits
โ โ โโโ extractor.rs # Type extractors
โ โ โโโ router.rs # Routing logic
โ โ โโโ state.rs # State management
โ โ โโโ error.rs # Error types
โ โ โโโ static_files.rs # Static file serving
โ โโโ Cargo.toml
โโโ wsforge-macros/ # Procedural macros
โ โโโ src/
โ โ โโโ lib.rs
โ โโโ Cargo.toml
โโโ wsforge/ # Main crate (re-exports)
โ โโโ src/
โ โ โโโ lib.rs
โ โโโ Cargo.toml
โโโ examples/ # Example applications
โ โโโ echo/ # Simple echo server
โ โโโ chat/ # CLI chat application
โ โโโ chat-web/ # Web-based chat with UI
โ โโโ realtime-game/ # Real-time game example
โโโ docs/ # Documentation
โโโ CONTRIBUTING.md # Contribution guidelines
โโโ LICENSE # MIT License
โโโ README.md # This file
- Getting Started - Your first WebSocket server
- Installation Guide - Detailed setup instructions
- Handlers - Writing handler functions
- Extractors - Type-safe data extraction
- Broadcasting - Sending messages to multiple clients
- State Management - Sharing data across connections
- API Reference - Complete API documentation
- Troubleshooting - Common issues and solutions
# Simple echo server
cargo run --example echo
# CLI chat application
cargo run --example chat
# Web chat with beautiful UI
cargo run --example chat-web
# Open http://127.0.0.1:8080 in your browser
# Real-time game server
cargo run --example realtime-game
Web Chat (examples/chat-web):
- Beautiful gradient UI with dark mode
- Real-time message broadcasting
- User join/leave notifications
- Live user count display
- Auto-reconnection on disconnect
- LocalStorage for username persistence
Handlers are async functions that process WebSocket messages:
// Simple handler
async fn simple() -> Result<String> {
Ok("Hello!".to_string())
}
// Handler with extractors
async fn complex(
Json(data): Json<MyStruct>,
conn: Connection,
State(manager): State<Arc<ConnectionManager>>,
) -> Result<JsonResponse<Response>> {
// Your logic here
}Type-safe data extraction from messages and context:
| Extractor | Description |
|---|---|
Message |
Raw WebSocket message |
Json<T> |
Deserialize JSON automatically |
Connection |
Access to active connection |
State<T> |
Shared application state |
ConnectInfo |
Connection metadata |
Data |
Raw binary data |
Send messages to multiple connections efficiently:
// Broadcast to all
manager.broadcast(msg);
// Broadcast except sender
manager.broadcast_except(conn.id(), msg);
// Broadcast to specific connections
manager.broadcast_to(&["conn_1", "conn_2"], msg);WsForge is designed for high performance:
- 47K+ requests/second for simple echo operations
- Sub-millisecond latency for message routing
- Lock-free connection management using DashMap
- Zero-copy message handling where possible
- Linear scaling with connection count
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
# Clone the repository
git clone https://github.com/aarambhdevhub/wsforge.git
cd wsforge
# Build the project
cargo build --all
# Run tests
cargo test --all
# Run examples
cargo run --example echo
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with tokio-tungstenite
- Inspired by Axum
- Thanks to the amazing Rust community
- GitHub: aarambhdevhub/wsforge
- Documentation: docs.rs/wsforge
- Crates.io: crates.io/crates/wsforge
- YouTube: @AarambhDevHub
- Issues: GitHub Issues
- Questions? Open a GitHub Discussion
- Bug Reports: GitHub Issues
- YouTube Tutorials: @AarambhDevHub
If you find WsForge useful, please consider giving it a โญ on GitHub! It helps others discover the project.
Made with โค๏ธ by Aarambh Dev Hub
Building the future of real-time applications in Rust