Skip to content

coseto6125/websocket-rs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

WebSocket-RS πŸš€

Tests Release License: MIT

English | 繁體中文

High-performance WebSocket client implementation in Rust with Python bindings. Provides both sync and async APIs with optional compatibility layer for websockets library.

🎯 Performance Overview

When to Use What

For Request-Response Patterns (chat apps, API calls, gaming):

  • πŸ₯‡ picows: 0.034 ms RTT - Best for extreme low-latency requirements
  • πŸ₯ˆ websocket-rs Sync: 0.128 ms RTT - Best balance of performance and simplicity
  • πŸ₯‰ websocket-client: 0.237 ms RTT - Good for simple sync applications

For High-Concurrency Pipelining (data streaming, batch processing):

  • πŸ₯‡ websocket-rs Async: 2.964 ms RTT - 12x faster than picows, 21x faster than websockets
  • πŸ₯ˆ picows: 36.129 ms RTT - Struggles with pipelined batches
  • πŸ₯‰ websockets Async: 61.217 ms RTT - Pure Python limitations

Why Different Patterns Matter

WebSocket applications use two fundamentally different communication patterns:

  1. Request-Response (RR): Send one message β†’ wait for reply β†’ send next

    • Used by: Chat apps, API calls, online games, command-response systems
    • Characteristics: Sequential, blocking, no concurrency
    • Winner: picows (event-driven C extension)
  2. Pipelined: Send multiple messages without waiting β†’ receive all responses

    • Used by: Data streaming, bulk operations, high-throughput systems
    • Characteristics: Concurrent, non-blocking, batched I/O
    • Winner: websocket-rs Async (Rust async with Tokio)

πŸ“Š View Detailed Benchmarks - Comprehensive performance comparison with test methodology

✨ What's New in v0.4.1

Changes

  • Fixed version number sync across all package files
  • Cleaned up project structure (removed obsolete python/ directory)
  • Improved .gitignore rules for better precision
  • Added Cargo.lock to version control
  • Created separate BENCHMARKS.md for detailed performance data

v0.4.0 Highlights

Pure Sync Client - Reimplemented using tungstenite (non-async):

  • Request-Response RTT: 0.128 ms (was 0.244 ms, 1.9x faster)
  • 1.85x faster than websocket-client
  • 6.2x faster than websockets

Architecture Design:

  • Sync client: Pure blocking I/O (simple scripts, CLI tools)
  • Async client: Tokio runtime (high concurrency, event-driven)

Backward Compatibility:

  • 100% API compatible
  • No code changes required

πŸš€ Quick Start

Installation

# From PyPI (recommended)
pip install websocket-rs

# Using uv
uv pip install websocket-rs

# From source
pip install git+https://github.com/coseto6125/websocket-rs.git

Basic Usage

# Direct usage - Sync API
from websocket_rs.sync_client import connect

with connect("ws://localhost:8765") as ws:
    ws.send("Hello")
    response = ws.recv()
    print(response)
# Direct usage - Async API
import asyncio
from websocket_rs.async_client import connect

async def main():
    ws = await connect("ws://localhost:8765")
    try:
        await ws.send("Hello")
        response = await ws.recv()
        print(response)
    finally:
        await ws.close()

asyncio.run(main())
# Monkeypatch mode (zero code changes)
import websocket_rs
websocket_rs.enable_monkeypatch()

# Existing code using websockets now uses Rust implementation
import websockets.sync.client
with websockets.sync.client.connect("ws://localhost:8765") as ws:
    ws.send("Hello")
    print(ws.recv())

πŸ“– API Documentation

Standard API (Compatible with Python websockets)

Method Description Example
connect(url) Create and connect WebSocket ws = connect("ws://localhost:8765")
send(message) Send message (str or bytes) ws.send("Hello")
recv() Receive message msg = ws.recv()
close() Close connection ws.close()

Connection Parameters

connect(
    url: str,                    # WebSocket server URL
    connect_timeout: float = 30, # Connection timeout (seconds)
    receive_timeout: float = 30  # Receive timeout (seconds)
)

🎯 Choosing the Right Implementation

Choose picows if you need:

  • βœ… Absolute lowest latency (<0.1 ms)
  • βœ… Request-response pattern (chat, API calls)
  • βœ… Team comfortable with event-driven callbacks
  • ❌ NOT for: Batch/pipelined operations

Choose websocket-rs Sync if you need:

  • βœ… Simple blocking API
  • βœ… Good performance (0.1-0.13 ms RTT)
  • βœ… Drop-in replacement for websockets.sync
  • βœ… Request-response pattern
  • βœ… 1.85x faster than websocket-client
  • ❌ NOT for: Async/await integration

Choose websocket-rs Async if you need:

  • βœ… High-concurrency pipelining
  • βœ… Batch operations (12x faster than picows)
  • βœ… Data streaming applications
  • βœ… Integration with Python asyncio
  • ❌ NOT for: Simple request-response (use Sync instead)

Choose websockets (Python) if you need:

  • βœ… Rapid prototyping
  • βœ… Mature ecosystem
  • βœ… Comprehensive documentation
  • βœ… Low-frequency communication (<10 msg/s)
  • ❌ NOT for: High-performance requirements

πŸ”§ Advanced Installation

From GitHub Releases (Pre-built wheels)

# Specify version (example for Linux x86_64, Python 3.12+)
uv pip install https://github.com/coseto6125/websocket-rs/releases/download/v0.4.1/websocket_rs-0.4.1-cp312-abi3-linux_x86_64.whl

From Source

Requirements:

git clone https://github.com/coseto6125/websocket-rs.git
cd websocket-rs
pip install maturin
maturin develop --release

Using in pyproject.toml

[project]
dependencies = [
    "websocket-rs @ git+https://github.com/coseto6125/websocket-rs.git@main",
]

πŸ§ͺ Running Tests and Benchmarks

# Run API compatibility tests
python tests/test_compatibility.py

# Run comprehensive benchmarks (RR + Pipelined)
python tests/benchmark_server_timestamp.py

# Run optimized benchmarks
python tests/benchmark_optimized.py

πŸ› οΈ Development

Local Development with uv (Recommended)

# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh

# Setup development environment
make install  # Creates venv and installs dependencies

# Build and test
make dev      # Development build
make test     # Run tests
make bench    # Run benchmarks

# Or manually with uv
uv venv
source .venv/bin/activate
uv pip install -e ".[dev]"
maturin develop --release

Traditional Development (pip)

# Install development dependencies
pip install maturin pytest websockets

# Development mode (fast iteration)
maturin develop

# Release mode (best performance)
maturin develop --release

# Watch mode (auto-recompile)
maturin develop --release --watch

πŸ“ Technical Architecture

Why Rust for WebSockets?

  1. Zero-cost abstractions: Rust's async/await compiles to efficient state machines
  2. Tokio runtime: Work-stealing scheduler optimized for I/O-bound tasks
  3. No GIL: True parallelism for concurrent operations
  4. Memory safety: No segfaults, data races, or memory leaks

Performance Trade-offs

Request-Response Mode:

  • ❌ PyO3 FFI overhead on every call
  • ❌ Dual runtime coordination (asyncio + Tokio)
  • βœ… Still competitive with pure Python sync
  • βœ… Better than Python async for large messages

Pipelined Mode:

  • βœ… FFI overhead amortized across batch
  • βœ… Tokio's concurrency advantages shine
  • βœ… No GIL blocking
  • βœ… Significant speedup over all Python alternatives

πŸ› Troubleshooting

Compilation Issues

# Check Rust version
rustc --version  # Requires >= 1.70

# Clean and rebuild
cargo clean
maturin develop --release

# Verbose mode
maturin develop --release -v

Runtime Issues

  • TimeoutError: Increase connect_timeout parameter
  • Module not found: Run maturin develop first
  • Connection refused: Check if server is running
  • Performance not as expected: Ensure using --release build

🀝 Contributing

Contributions welcome! Please ensure:

  1. All tests pass
  2. API compatibility is maintained
  3. Performance benchmarks included
  4. Documentation updated

πŸ“„ License

MIT License - See LICENSE

πŸ™ Acknowledgments

πŸ“š Further Reading

About

High-performance WebSocket client library for Python using Rust

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •