2 releases

0.1.1 Apr 19, 2024
0.1.0 Apr 15, 2024
0.0.0 Apr 13, 2024

#67 in WebSocket

Download history 172/week @ 2024-04-08 309/week @ 2024-04-15 12/week @ 2024-04-22

493 downloads per month

MIT license

12KB
226 lines

Pws

Persistent Websocket connection for tokio-tungstenite.

Example

See more examples in the examples folder.

use pws::{connect_persistent_websocket_async, Message, Url};
use std::str::FromStr;

#[tokio::main]
async fn main() {
    let url = Url::from_str("wss://echo.websocket.org").unwrap();
    let (tx, mut rx) = connect_persistent_websocket_async(url).await.unwrap();
    let mut close_count = 0;
    while let Ok(msg) = rx.recv().await {
        match msg {
            Message::Text(msg) => {
                println!("received: {msg}");
                // Simulate a connection close.
                tx.send(Message::Close(None)).await.unwrap();
            }
            Message::ConnectionOpened => {
                println!("connection opened ({close_count})");
                let msg = format!("hello! connection #{close_count}");
                tx.send(Message::Text(msg)).await.unwrap();
            }
            Message::ConnectionClosed => {
                println!("connection closed");
                close_count += 1;
                if close_count >= 2 {
                    // Terminate the persistent connection.
                    break;
                }
            }
            _ => {}
        }
    }
    println!("persistent websocket is done");
}

Dependencies

~6–17MB
~249K SLoC