3 releases (breaking)

0.3.0 Apr 16, 2024
0.2.0 Feb 21, 2024
0.1.0 Feb 14, 2024

#49 in WebSocket

Download history 45/week @ 2024-02-12 154/week @ 2024-02-19 80/week @ 2024-02-26 168/week @ 2024-03-04 72/week @ 2024-03-11 204/week @ 2024-03-18 102/week @ 2024-03-25 381/week @ 2024-04-01 314/week @ 2024-04-08 401/week @ 2024-04-15 438/week @ 2024-04-22 353/week @ 2024-04-29 539/week @ 2024-05-06

1,759 downloads per month
Used in elgato-control-center

MIT license

33KB
674 lines

reqwest-websocket

crates.io Documentation MIT

Extension for reqwest to allow websocket connections.

This crate contains the extension trait RequestBuilderExt which adds an upgrade method to reqwest::ReqestBuilder that will prepare the HTTP request to upgrade the connection to a WebSocket. After you call upgrade(), you can send your upgraded request like usual with send() which will return an UpgradeResponse. The UpgradeResponse wraps reqwest::Response (and also dereferences to it), so you can inspect the response if you need to. Finally you can use into_websocket() on the response to turn it into a async stream and sink for messages. Both text and binary messages are supported.

Example

For a full example take a look at hello_world.rs.

// extends the reqwest::RequestBuilder to allow websocket upgrades
use reqwest_websocket::RequestBuilderExt;

// create a GET request, upgrade it and send it.
let response = Client::default()
    .get("wss://echo.websocket.org/")
    .upgrade() // <-- prepares the websocket upgrade.
    .send()
    .await?;

// turn the response into a websocket stream
let mut websocket = response.into_websocket().await?;

// the websocket implements `Sink<Message>`.
websocket.send(Message::Text("Hello, World".into())).await?;

// the websocket is also a `TryStream` over `Message`s.
while let Some(message) = websocket.try_next().await? {
    match message {
        Message::Text(text) => println!("{text}"),
        _ => {}
    }
}

Support for WebAssembly

reqwest-websocket uses the HTTP upgrade functionality built in in reqwest, which is not available on WebAssembly. When you use reqwest-websocket in WebAssembly, it falls back to using web_sys::WebSocket. That means that everything except URL (including query parameters) is not used for your request.

Dependencies

~6–22MB
~285K SLoC