How can set a timeout when reading data using tokio::BufReader

Hello everyone

i wrote a little app, that reads some data from an endpoint and transform it in another. the problem i have is that the data i read may send incorrect length, this is a simplified example of the payload i receive on my end


len: 100 bytes

in my app i use a loop with a bufreader, something like this

      // reader is tokio::io::BufReader
      while let Ok(len) = buf).await {
          // process my buffer      

the problem i am having is that sometime the length of the content i receive in the payload is not correct, and in my while loop i am calculating the number of bytes i received and compared them to the expected length, and based on that i break the loop.

when the payload len is not correct, the loop hang and it keep wating for more data to come, i would like to set a timeout on the read, and break the loop once the timeout is finished, or simply error back that the len is incorrect.

Tokio provides a timeout function you can use like this:

let my_duration = tokio::time::Duration::from_millis(500);
while let Ok(len) = timeout(my_duration, buf)).await {

thank you @alice you are a real savior :smiling_face_with_three_hearts: :smiling_face_with_three_hearts:

another question, probably related, is there a way to set the timeout on task::spawn ?

You can wrap the task in timeout before spawning it.

1 Like

@alice :kissing_heart: :kissing_heart: you saved me :innocent: :innocent:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.