Reading from a TcpStream with Read::read_to_string hangs until the connection is closed by the remote end

Check out the docs for Read::read_to_string, emphasis mine:

Read all bytes until EOF in this source, placing them into buf.

Likewise for Read::read_to_end:

Read all bytes until EOF in this source, placing them into buf.

Notably, you aren’t reading 512 bytes in the first example, you are pre-allocating 512 bytes of space and then reading every byte until the socket closes – 4 minutes later.

It sounds like you want to use BufRead::read_line:

Read all bytes until a newline byte (the 0xA byte) is reached, and append them to the provided buffer.

This function will continue to read (and buffer) bytes from the underlying stream until the newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf.

You can also any other technique that will read a fixed amount of data before returning. One such example would be Read::take, which will cap the total number of bytes you can read at a time.

Leave a Comment