3 releases (breaking)

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

#55 in WebSocket

Download history 41/week @ 2024-02-11 153/week @ 2024-02-18 73/week @ 2024-02-25 175/week @ 2024-03-03 70/week @ 2024-03-10 198/week @ 2024-03-17 104/week @ 2024-03-24 376/week @ 2024-03-31 302/week @ 2024-04-07 412/week @ 2024-04-14 409/week @ 2024-04-21

1,503 downloads per month

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–18MB
~270K SLoC