5 releases (3 breaking)

new 0.4.1 Jul 9, 2024
0.4.0 Jun 26, 2024
0.3.0 Apr 16, 2024
0.2.0 Feb 21, 2024
0.1.0 Feb 14, 2024

#25 in WebSocket

Download history 128/week @ 2024-03-14 181/week @ 2024-03-21 241/week @ 2024-03-28 317/week @ 2024-04-04 417/week @ 2024-04-11 280/week @ 2024-04-18 515/week @ 2024-04-25 366/week @ 2024-05-02 833/week @ 2024-05-09 778/week @ 2024-05-16 767/week @ 2024-05-23 847/week @ 2024-05-30 1008/week @ 2024-06-06 1220/week @ 2024-06-13 1284/week @ 2024-06-20 875/week @ 2024-06-27

4,541 downloads per month
Used in 2 crates

MIT license

53KB
988 lines

reqwest-websocket

crates.io Documentation MIT Build

Extension for reqwest to allow websocket connections.

This crate contains the extension trait RequestBuilderExt, which adds an upgrade method to reqwest::RequestBuilder that prepares the HTTP request to upgrade the connection to a WebSocket. After you call upgrade(), you can send your upgraded request as 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 needed. Finally, you can use into_websocket() on the response to turn it into an 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;

// Creates a GET request, upgrades and sends it.
let response = Client::default()
    .get("wss://echo.websocket.org/")
    .upgrade() // Prepares the WebSocket upgrade.
    .send()
    .await?;

// Turns 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? {
    if let Message::Text(text) = message {
        println!("received: {text}")
    }
}

Support for WebAssembly

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

Dependencies

~4–19MB
~242K SLoC