Crate axum_tungstenite

source ·
Expand description

WebSocket connections for axum directly using tungstenite.

Differences from axum::extract::ws

axum already supports WebSockets through axum::extract::ws. However the fact that axum uses tungstenite under the hood is a private implementation detail. Thus axum doesn’t directly expose types from tungstenite, such as tungstenite::Error and tungstenite::Message. This allows axum to update to a new major version of tungstenite in a new minor version of axum, which leads to greater API stability.

This library works differently as it directly uses the types from tungstenite in its public API. That makes some things simpler but also means axum-tungstenite will receive a new major version when tungstenite does.

Which should you choose?

By default you should use axum::extract::ws unless you specifically need something from tungstenite and don’t mind keeping up with additional breaking changes.

Example

use axum::{
    routing::get,
    response::IntoResponse,
    Router,
};
use axum_tungstenite::{WebSocketUpgrade, WebSocket};

let app = Router::new().route("/ws", get(handler));

async fn handler(ws: WebSocketUpgrade) -> impl IntoResponse {
    ws.on_upgrade(handle_socket)
}

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let msg = if let Ok(msg) = msg {
            msg
        } else {
            // client disconnected
            return;
        };

        if socket.send(msg).await.is_err() {
            // client disconnected
            return;
        }
    }
}

Re-exports

pub use tokio_tungstenite::tungstenite::error::CapacityError;
pub use tokio_tungstenite::tungstenite::error::Error;
pub use tokio_tungstenite::tungstenite::error::ProtocolError;
pub use tokio_tungstenite::tungstenite::error::TlsError;
pub use tokio_tungstenite::tungstenite::error::UrlError;
pub use tokio_tungstenite::tungstenite::Message;

Modules

WebSocket specific rejections.

Structs

The default OnFailedUpdgrade used by WebSocketUpgrade.
A stream of WebSocket messages.
Extractor for establishing WebSocket connections.

Traits

What to do when a connection upgrade fails.