#web-framework #web #framework

axum-typed-websockets

axum::extract::ws with type safe messages

6 releases (breaking)

0.6.0 Dec 31, 2023
0.5.0 Apr 15, 2023
0.4.0 May 8, 2022
0.3.0 Dec 2, 2021
0.1.0 Oct 30, 2021

#2126 in Web programming

Download history 161/week @ 2024-07-02 168/week @ 2024-07-09 213/week @ 2024-07-16 209/week @ 2024-07-23 223/week @ 2024-07-30 182/week @ 2024-08-06 187/week @ 2024-08-13 128/week @ 2024-08-20 271/week @ 2024-08-27 150/week @ 2024-09-03 159/week @ 2024-09-10 182/week @ 2024-09-17 161/week @ 2024-09-24 162/week @ 2024-10-01 184/week @ 2024-10-08 141/week @ 2024-10-15

683 downloads per month

MIT license

17KB
298 lines

axum-typed-websockets

axum::extract::ws with type safe messages.

Build status Crates.io Documentation

More information about this crate can be found in the crate documentation.


lib.rs:

axum::extract::ws with type safe messages.

Example

use axum::{
    Router,
    response::IntoResponse,
    routing::get,
};
use axum_typed_websockets::{Message, WebSocket, WebSocketUpgrade};
use serde::{Serialize, Deserialize};
use std::time::Instant;

// Make a regular axum router
let app = Router::new().route("/ws", get(handler));

// Run it!
axum::serve(
    tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap(),
    app.into_make_service()
)
.await
.unwrap();

async fn handler(
    // Upgrade the request to a WebSocket connection where the server sends
    // messages of type `ServerMsg` and the clients sends `ClientMsg`
    ws: WebSocketUpgrade<ServerMsg, ClientMsg>,
) -> impl IntoResponse {
    ws.on_upgrade(ping_pong_socket)
}

// Send a ping and measure how long time it takes to get a pong back
async fn ping_pong_socket(mut socket: WebSocket<ServerMsg, ClientMsg>) {
    let start = Instant::now();
    socket.send(Message::Item(ServerMsg::Ping)).await.ok();

    if let Some(msg) = socket.recv().await {
        match msg {
            Ok(Message::Item(ClientMsg::Pong)) => {
                println!("ping: {:?}", start.elapsed());
            },
            Ok(_) => {},
            Err(err) => {
                eprintln!("got error: {}", err);
            },
        }
    }
}

#[derive(Debug, Serialize)]
enum ServerMsg {
    Ping,
}

#[derive(Debug, Deserialize)]
enum ClientMsg {
    Pong,
}

Feature flags

The following features are available:

  • json: Enables JsonCodec which encodes message as JSON using serde_json. Enabled by default.

Dependencies

~8–14MB
~175K SLoC