Tokio time delay drops the tcp connection or TcpStream made with tokio net tcpListener

i am using tcpListners to get TcpStream on which i am using a loop to read bytes from this stream, the loop is consuming too much cpu usage so i was trying to use time dalay and interval functions from tokio::time but when these are used inside to the loop the tcpStream gets disconneted??

 `fn read_from_stream(){`

  let mut interval = time::interval(time::Duration::from_millis(1000));
      let mut buff = [0,1024]; buff).await{
          //both of these drops the connection


That code has a buffer that is only two bytes long which might explain the high cpu usage. Try (note the semi colon instead of the comma)

let mut buff = [0; 1024];

And see if it helps with the cpu.

EDIT: Iā€™m guessing using a small buffer plus the delays was probably why the stream was dropping because it was likely timing out. Since you had effectively dropped your read rate to a few hundred bytes per second or something

its not a problem with buffer just tested still not working

Are you sending data at a high rate to the tcp port? Or are you doing something else thats cpu intensive once the data is read? I'm not immediately seeing why you're having a problem.

This is already very suspicious.

Before trying to fix it with delays and whatever it would be better to find out what is going on.

For example, in that code you loop around and never check what is the Err(_). So I suspect that if every results in an error you are looping like crazy going nowhere and consuming lot's or CPU time doing so.

Check your error returns.

No doubt that will provide a clue as to what the real problem is.

1 Like

Besides error returns, remember to check for reads of length zero as they indicate EOF.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.