2 releases

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

#182 in WebSocket

Download history 9/week @ 2024-07-30 1/week @ 2024-09-17 7/week @ 2024-09-24

144 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–18MB
~232K SLoC