Expand description
§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
// [dependencies]
// axum = "0.7"
// axum-tws = "0.1"
// tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use axum::{response::Response, routing::get, Router};
use axum_tws::{Message, WebSocket, WebSocketUpgrade};
#[tokio::main]
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(())
}
§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.
Re-exports§
pub use crate::upgrade::WebSocketUpgrade;
pub use crate::websocket::WebSocket;
Modules§
- General error type used in the crate.
- This module contains a correct and complete implementation of RFC6455.
- Implementation of a WebSocket server.
- Wrapper types for TLS functionality, abstracting over
rustls
andnative-tls
connector and stream types.
Structs§
- Close status code.
- Low-level configuration for a
WebSocketStream
that allows configuring behavior for sending and receiving messages. - Configuration for limitations on reading of
Message
s from aWebSocketStream
to prevent high memory usage caused by malicious actors. - A WebSocket message. This is cheaply clonable and uses
Payload
as the payload storage underneath. - Builder for WebSocket server connections.
- A WebSocket stream that full messages can be read from and written to.
Enums§
- A reusable TLS connector for wrapping streams.
- Generic error when using WebSockets with this crate.
- A stream that might be protected with TLS.