A high-performance WebSocket backend for axum powered by tokio-websockets.
Find a file
2025-01-16 17:55:42 -05:00
.github/workflows Add standard ci workflow 2025-01-16 17:55:36 -05:00
examples Add a runnable example 2025-01-16 17:50:44 -05:00
src Fix clippy lint 2025-01-16 17:55:42 -05:00
.gitignore Update .gitignore 2024-02-15 00:20:24 -05:00
Cargo.toml Add a runnable example 2025-01-16 17:50:44 -05:00
CHANGELOG.md Update CHANGELOG.md 2025-01-16 17:25:56 -05:00
LICENSE-APACHE Initial commit 2024-01-31 22:27:24 -05:00
LICENSE-MIT Initial commit 2024-01-31 22:27:24 -05:00
README.md Update README.md 2025-01-16 17:50:50 -05:00

axum-tws


axum-tws is an alternative WebSocket extractor for axum using tokio-websockets as the underlying WebSocket library instead of tungstenite.

It is not a complete drop-in replacement and has no intention to be one. While your upgrade handler will look the same, working with Message types in tokio-websockets is slightly different from tungstenite. Please refer to the tokio-websockets documentation for detailed information, or take a look at the example below.

Much of the code has been ported directly from the axum::extract::ws module - all credit goes to the original authors.

Getting Started

Run cargo add axum-tws to add the library to your project.

Echo Server Example

If you have cloned the axum-tws repository, you can run the echo_server example with the command cargo run --example echo_server. You can then connect to it with wscat or similar on 127.0.0.1:3000/ws.

use axum::{response::Response, routing::get, Router};
use axum_tws::{WebSocket, WebSocketUpgrade};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;

    axum::serve(listener, Router::new().route("/ws", get(handle_upgrade))).await?;

    Ok(())
}

async fn handle_upgrade(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade({
        move |socket| async {
            if let Err(e) = handle_ws(socket).await {
                println!("websocket error: {:?}", e);
            }
        }
    })
}

async fn handle_ws(mut socket: WebSocket) -> Result<(), Box<dyn std::error::Error>> {
    while let Some(Ok(msg)) = socket.recv().await {
        if msg.is_text() {
            socket.send(msg).await?;
        }
    }

    Ok(())
}

Feature Flags

Flag Default Description
http2 Disabled Adds support for WebSockets over HTTP/2

Contributing

Contributions are always welcome! If you have an idea for a feature or find a bug, let me know. PR's are appreciated, but if it's not a small change, please open an issue first so we're all on the same page!

License

axum-tws is dual-licensed under either

at your option.