| Crates.io | stream-tungstenite |
| lib.rs | stream-tungstenite |
| version | 0.5.1 |
| created_at | 2024-10-23 08:46:57.113438+00 |
| updated_at | 2025-07-03 08:30:49.004264+00 |
| description | A streaming implementation of the Tungstenite WebSocket protocol |
| homepage | |
| repository | |
| max_upload_size | |
| id | 1419843 |
| size | 156,807 |
stream-tungstenite is a powerful Rust WebSocket client library designed for applications requiring reliable connections. It provides automatic reconnection, connection state management, extension mechanisms, and detailed metrics collection.
use stream_tungstenite::prelude::*;
use std::sync::Arc;
#[tokio::main]
async fn main() {
// Create client with default configuration
let client = Arc::new(ReconnectT::new("wss://echo.websocket.org", None));
// Create message receiving stream
let mut receive_stream = client.create_receive_stream().await;
// Run client in background
let client_clone = client.clone();
tokio::spawn(async move {
client_clone.run().await;
});
// Send message
let message = tokio_tungstenite::tungstenite::Message::Text("Hello WebSocket!".into());
client.sender.send(message).await.unwrap();
// Receive message
if let Some(received) = receive_stream.next().await {
println!("Received message: {:?}", received);
}
}
use stream_tungstenite::prelude::*;
use std::sync::Arc;
#[tokio::main]
async fn main() {
// Use fast reconnection configuration (from src/config.rs)
let config = ReconnectOptions::fast_reconnect();
let client = Arc::new(ReconnectT::new("wss://echo.websocket.org", Some(config)));
client.run().await;
}
use stream_tungstenite::prelude::*;
use futures_util::StreamExt;
use std::sync::Arc;
#[tokio::main]
async fn main() {
let client = Arc::new(ReconnectT::new("wss://echo.websocket.org", None));
// Create status stream
let mut status_stream = client.create_status_stream().await;
// Start client
let client_clone = client.clone();
tokio::spawn(async move {
client_clone.run().await;
});
// Monitor status changes
while let Some(status) = status_stream.next().await {
match status {
ConnectionStatus::Connected => println!("✅ Connected"),
ConnectionStatus::Disconnected => println!("❌ Disconnected"),
}
}
}
use stream_tungstenite::prelude::*;
use std::time::Duration;
let custom_strategy = ExpBackoffStrategy::new(
Duration::from_millis(500), // Initial delay
2.0, // Growth factor
0.1 // Jitter factor
).with_max(Duration::from_secs(30));
let config = ReconnectOptions::default()
.with_exp_backoff_strategy(custom_strategy)
.with_receive_timeout(Duration::from_secs(15));
let client = ReconnectT::new("wss://example.com", Some(config));
The library provides three preset configurations for different scenarios (from src/config.rs):
fast_reconnect()Suitable for scenarios requiring quick connection recovery:
stable_connection()Suitable for scenarios requiring long-term stable connections:
low_latency()Suitable for latency-sensitive scenarios:
You can add custom functionality by implementing the Extension trait:
use stream_tungstenite::prelude::*;
// Register extension
let client = Arc::new(ReconnectT::new("wss://example.com", None));
client.register_extension(your_extension).await.unwrap();
// Get connection state snapshot (from src/tungstenite.rs)
let state = client.get_connection_state().await;
println!("Connection ID: {}", state.connection_id);
println!("Status: {:?}", state.status);
println!("Reconnect count: {}", state.reconnect_count);
println!("Error count: {}", state.error_count);
// Check if connection is healthy
let is_healthy = client.is_connection_healthy();
println!("Connection healthy: {}", is_healthy);
The library provides structured error handling mechanisms (from src/errors.rs):
use stream_tungstenite::prelude::*;
// Errors are automatically recorded in connection state
let state = client.get_connection_state().await;
if let Some(last_error) = state.last_error {
println!("Last error: {:?}", last_error);
}
ExpBackoffStrategy provides flexible exponential backoff reconnection mechanism (from src/strategies.rs):
use stream_tungstenite::prelude::*;
use std::time::Duration;
let strategy = ExpBackoffStrategy::new(
Duration::from_secs(1), // Initial delay
2.0, // Double delay each retry
0.05 // 5% random jitter
)
.with_max(Duration::from_secs(60)) // Maximum delay not exceeding 60 seconds
.with_seed(12345); // Optional: set random seed
let config = ReconnectOptions::default()
.with_exp_backoff_strategy(strategy);
Add dependency to your Cargo.toml:
[dependencies]
stream-tungstenite = "0.4.0"
tokio = { version = "1.0", features = ["full"] }
This project is licensed under the Apache License Version 2.0. See the LICENSE file for details.
Contributions are welcome! Please feel free to submit Pull Requests or create Issues to report bugs and suggest improvements.