ws-reconnect-client 0.1.0

Async WebSocket client with automatic reconnection, exponential backoff, and typed JSON message parsing
Documentation

ws-reconnect-client

Async WebSocket client for Rust with automatic reconnection and typed JSON message parsing.

Features

  • Automatic reconnection with exponential backoff
  • Generic typed JSON message parsing (WebSocketClient<T>)
  • Automatic PING/PONG handling
  • Stream-based API (MessageStream<T> implements futures::Stream)
  • Builder pattern for configuration
  • Built on tokio-tungstenite

Installation

[dependencies]
ws-reconnect-client = "0.1"

Quick Start

use ws_reconnect_client::{WebSocketClientBuilder, WsConnectionConfig};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct MyMessage {
    data: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = WebSocketClientBuilder::new("wss://example.com/ws")
        .ping_interval(30)
        .auto_reconnect(true)
        .max_retries(10)
        .build::<MyMessage>();

    client.listen(None::<()>, |msg| {
        println!("Received: {:?}", msg);
        Ok(())
    }).await?;

    Ok(())
}

Configuration

use ws_reconnect_client::WsConnectionConfig;

let config = WsConnectionConfig::new("wss://example.com/ws")
    .with_retries(10)              // Max reconnection attempts (default: 20)
    .with_backoff(100, 10_000)     // Initial/max backoff in ms (default: 100ms, 10s)
    .with_ping_interval(5)         // Ping interval in seconds (default: 5, 0 to disable)
    .with_auto_reconnect(true);    // Auto-reconnect on disconnect (default: true)

Low-Level API

For manual control over the connection:

use ws_reconnect_client::{connect_with_retry, WsConnectionConfig, send_subscription};
use futures_util::StreamExt;

let config = WsConnectionConfig::new("wss://example.com/ws");
let (mut writer, mut reader) = connect_with_retry(&config).await?;

// Send a subscription
send_subscription(&mut writer, &serde_json::json!({"type": "subscribe"})).await?;

// Read messages
while let Some(msg) = reader.next().await {
    println!("{:?}", msg);
}

License

MIT