Skip to content

๐Ÿ”ฅ WsForge - High-performance WebSocket framework for Rust. Build real-time applications with type-safe extractors, flexible handlers, and built-in broadcasting. Inspired by Axum, powered by tokio-tungstenite. Features: async/await, zero-copy optimizations, hybrid HTTP/WebSocket server.

License

Notifications You must be signed in to change notification settings

AarambhDevHub/wsforge

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

10 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ”ฅ WsForge

High-Performance WebSocket Framework for Rust

Rust License: MIT GitHub Stars

Build real-time applications with ease and exceptional performance

Documentation | Examples | API Reference | YouTube


โœจ Features

  • ๐Ÿš€ 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

๐Ÿš€ Quick Start

Installation

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"

Echo Server Example

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(())
}

Chat Server Example

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(())
}

๐Ÿ“ Project Structure

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

๐Ÿ“– Documentation

๐ŸŽฎ Examples

Run Examples

# 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

Example Features

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

๐ŸŽฏ Key Concepts

Handlers

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
}

Extractors

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

Broadcasting

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);

๐Ÿ“Š Performance

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

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

Quick Contribution Steps

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Setup

# 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

๐Ÿ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

๐Ÿ”— Links

๐Ÿ’ฌ Community & Support

โญ Show Your Support

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

About

๐Ÿ”ฅ WsForge - High-performance WebSocket framework for Rust. Build real-time applications with type-safe extractors, flexible handlers, and built-in broadcasting. Inspired by Axum, powered by tokio-tungstenite. Features: async/await, zero-copy optimizations, hybrid HTTP/WebSocket server.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

  •  

Packages

No packages published

Languages