-
-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathhttp2_websocket.rs
More file actions
53 lines (43 loc) · 1.37 KB
/
Copy pathhttp2_websocket.rs
File metadata and controls
53 lines (43 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//! Run websocket server
//!
//! ```not_rust
//! git clone https://github.com/tokio-rs/axum && cd axum
//! cargo run -p example-websockets-http2
//! ```
use std::time::Duration;
use futures_util::{SinkExt, StreamExt, TryStreamExt};
use wreq::{Client, header, ws::Message};
#[tokio::main]
async fn main() -> wreq::Result<()> {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.init();
// Build a client
let client = Client::builder()
.connect_timeout(Duration::from_secs(10))
.cert_verification(false)
.build()?;
// Use the API you're already familiar with
let websocket = client
.websocket("wss://127.0.0.1:3000/ws")
.header(header::USER_AGENT, env!("CARGO_PKG_NAME"))
.read_buffer_size(1024 * 1024)
.use_http2()
.send()
.await?;
assert_eq!(websocket.version(), http::Version::HTTP_2);
let (mut tx, mut rx) = websocket.into_websocket().await?.split();
tokio::spawn(async move {
for i in 1..11 {
if let Err(err) = tx.send(Message::text(format!("Hello, World! #{i}"))).await {
eprintln!("failed to send message: {err}");
}
}
});
while let Some(message) = rx.try_next().await? {
if let Message::Text(text) = message {
println!("received: {text}");
}
}
Ok(())
}