Expand description
WebSocket support for Rocket.
This crate implements support for WebSockets via Rocket’s connection upgrade API and tungstenite.
§Usage
Depend on the crate. Here, we rename the dependency to ws for convenience:
[dependencies]
ws = { package = "rocket_ws", version = "0.1.1" }Then, use WebSocket as a request guard in any route and either call
WebSocket::channel() or return a stream via Stream! or
WebSocket::stream() in the handler. The examples below are equivalent:
#[get("/echo?channel")]
fn echo_channel(ws: ws::WebSocket) -> ws::Channel<'static> {
use rocket::futures::{SinkExt, StreamExt};
ws.channel(move |mut stream| Box::pin(async move {
while let Some(message) = stream.next().await {
let _ = stream.send(message?).await;
}
Ok(())
}))
}
#[get("/echo?stream")]
fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
ws::Stream! { ws =>
for await message in ws {
yield message?;
}
}
}
#[get("/echo?compose")]
fn echo_compose(ws: ws::WebSocket) -> ws::Stream!['static] {
ws.stream(|io| io)
}WebSocket connections are configurable via WebSocket::config():
#[get("/echo")]
fn echo_stream(ws: ws::WebSocket) -> ws::Stream!['static] {
let ws = ws.config(ws::Config {
max_send_queue: Some(5),
..Default::default()
});
ws::Stream! { ws =>
for await message in ws {
yield message?;
}
}
}Modules§
- frame
- Structures for constructing raw WebSocket frames.
- result
- Library
ErrorandResulttypes. - stream
- Types representing incoming and/or outgoing
asyncMessagestreams.
Macros§
Structs§
- Channel
- A streaming channel, returned by
WebSocket::channel(). - Config
- WebSocket connection configuration.
- WebSocket
- A request guard identifying WebSocket requests. Converts into a
ChannelorMessageStream.
Enums§
- Message
- A WebSocket message.