quinn-rs / quinn

Async-friendly QUIC implementation in Rust
Apache License 2.0
3.54k stars 360 forks source link

How to receive data in blocking way #1862

Closed wanyt closed 1 month ago

wanyt commented 1 month ago

In an MQTT communication scenario based on Quinn, the client needs to wait for data being sent by the server. How can the client wait to receive the data from the server? I am currently using a loop, but I feel that this approach consumes CPU resources excessively. Is there a way for the client to block and receive data?

this is my code:

loop {
        let resp = recv
            .read_to_end(usize::max_value())
            .await
            .map_err(|e| anyhow!("failed to read response: {}", e))?;
        let duration = response_start.elapsed();
        eprintln!(
            "response received in {:?} - {} KiB/s",
            duration,
            resp.len() as f32 / (duration_secs(&duration) * 1024.0)
        );

        io::stdout().write_all(&resp).unwrap();
        io::stdout().flush().unwrap();     
    }
djc commented 1 month ago

Why do you feel this approach consumes excessive CPU? Have you measured this?

Why do you even need a loop here? The recv.read_to_end() call should yield only once, after the entire response is available. In fact, polling this future more than once will probably yield undefined behavior.

wanyt commented 1 month ago

How should I continuously wait to receive data when I'm not sure when the data will come?

djc commented 1 month ago

Your async runtime will wake up your task when data has been received. But this is the basics of async Rust, and I don't think our issue tracker is the right place to explain the whole paradigm.