TcpStream Read Timeout in Rust

  Kiến thức lập trình

I am trying to write a recv(mut stream: TcpStream) function to read and return content read from a TcpStream. I want the function to read as much data as possible, only stopping when the EOF is encountered or a timeout is triggered.

I have tried to implement this using the TcpStream::read_to_end and TcpStream::set_read_timeout.

fn recv(mut stream: TcpStream) -> std::io::Result<Vec<u8>> {
    let mut buffer = Vec::new();

    stream.set_read_timeout(Some(Duration::from_secs(5)))?;

    if let Err(error) = stream.read_to_end(&mut buffer) {
        match error.kind() {
            ErrorKind::TimedOut | ErrorKind::WouldBlock => eprintln!("Read timed out"),
            _ => return Err(error),
        }
    }
    Ok(buffer)
}

However, this function never gets timeout out – it just keeps reading data forever.

Using TcpStream::read_exact instead of TcpStream::read_to_end fixes the timeout issue; however, this has a limited buffer size.

fn recv(mut stream: TcpStream) -> std::io::Result<[u8; MAX_FILE_SIZE]> {
    let mut buffer = [0; MAX_FILE_SIZE];

    stream.set_read_timeout(Some(Duration::from_secs(5)))?;

    if let Err(error) = stream.read_exact(&mut buffer) {
        match error.kind() {
            ErrorKind::UnexpectedEof => (),
            ErrorKind::TimedOut | ErrorKind::WouldBlock => eprintln!("Read timed out"),
            _ => return Err(error),
        }
    }
    Ok(buffer)
}

Is it possible to stop TcpStream::read_to_end by setting a read timeout? If not, is there another way to implement my requirements using std functions?

Thanks:)

New contributor

hkattt is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT