#reqwest #stream

reqwest-websocket

WebSocket connections with reqwest

7 unstable releases (3 breaking)

0.4.3 Oct 24, 2024
0.4.2 Aug 19, 2024
0.4.1 Jul 9, 2024
0.4.0 Jun 26, 2024
0.1.0 Feb 14, 2024

#21 in WebSocket

Download history 1129/week @ 2024-08-24 1083/week @ 2024-08-31 1201/week @ 2024-09-07 1388/week @ 2024-09-14 1573/week @ 2024-09-21 2126/week @ 2024-09-28 1947/week @ 2024-10-05 1549/week @ 2024-10-12 1957/week @ 2024-10-19 2279/week @ 2024-10-26 2022/week @ 2024-11-02 2085/week @ 2024-11-09 2256/week @ 2024-11-16 2052/week @ 2024-11-23 2415/week @ 2024-11-30 1647/week @ 2024-12-07

8,682 downloads per month
Used in 9 crates (5 directly)

MIT license

52KB
945 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–17MB
~213K SLoC