Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

50%
+2 −2
Q&A Read all data from TCP stream in Rust

One way to do this, is: Set a read timeout on the TcpStream using set_read_timeout. This avoids a hanging client in case the server has stopped sending but left the connection open. Read from t...

posted 12mo ago by Matthias Braun‭  ·  edited 12mo ago by Matthias Braun‭

Answer
#4: Post edited by user avatar Matthias Braun‭ · 2023-05-01T07:29:05Z (12 months ago)
add explanation about the client's assumption
  • One way to do this, is:
  • 1. Set a read timeout on the `TcpStream` using [`set_read_timeout`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.set_read_timeout). This avoids a hanging client in case the server has stopped sending but left the connection open.
  • 2. Read from the stream in a loop, using a [`BufReader`](https://doc.rust-lang.org/std/io/struct.BufReader.html), and aggregate the read bytes.
  • 3. Break out of the loop in case the read timed out or the server closed the connection.
  • Here's some example code:
  • use std::{
  • io::{self, BufReader, LineWriter, Read, Write},
  • net::TcpStream,
  • time::Duration,
  • };
  • fn main() -> io::Result<()> {
  • println!("Start of program");
  • // This is just to get data via TCP, we could of course parse the HTTP header for
  • // the message length
  • let server_host = "www.neverssl.com";
  • let server_port = "80";
  • let stream = TcpStream::connect(server_host.to_string() + ":" + server_port)?;
  • let mut reader = BufReader::new(&stream);
  • let mut writer = LineWriter::new(&stream);
  • // Don't block indefinitely on `reader.read` when there's no data to read
  • let max_read_time = Duration::from_millis(200);
  • stream.set_read_timeout(Some(max_read_time))?;
  • writer.write_all(format!("GET / HTTP/1.1\r\nhost: {server_host}\r\n\r\n").as_bytes())?;
  • let mut total_bytes_read = vec![];
  • let bytes_to_read_per_attempt = 1024;
  • let mut read_attempt_nr = 0;
  • loop {
  • read_attempt_nr += 1;
  • println!("Read attempt nr {read_attempt_nr}");
  • let mut cur_buffer = vec![0; bytes_to_read_per_attempt];
  • // If the reader has no data but the server hasn't closed the connection,
  • // by default `reader.read()` would block until the server closes the connection.
  • // Hence, we need `stream.set_read_timeout`.
  • let nr_of_bytes_read = match reader.read(&mut cur_buffer) {
  • Ok(nr_of_bytes_read) => nr_of_bytes_read,
  • Err(err) => {
  • if err.kind() == io::ErrorKind::WouldBlock || err.kind() == io::ErrorKind::TimedOut
  • {
  • println!("Read attempt timed out");
  • break;
  • } else {
  • return Err(err);
  • }
  • }
  • };
  • // Reading zero bytes indicates that the server closed the connection.
  • if nr_of_bytes_read == 0 {
  • println!("Read zero bytes → Connection seems closed");
  • break;
  • }
  • // Remove the excess null bytes at the end of cur_buffer
  • cur_buffer.truncate(nr_of_bytes_read);
  • total_bytes_read.append(&mut cur_buffer);
  • println!("Read {nr_of_bytes_read} bytes in attempt nr {read_attempt_nr}");
  • }
  • let response = String::from_utf8_lossy(&total_bytes_read).to_string();
  • let nr_of_bytes_received = total_bytes_read.len();
  • println!("Server response : {response}");
  • println!("{nr_of_bytes_received} bytes received");
  • Ok(println!("End of program"))
  • }
  • []()
  • One way to do this, is:
  • 1. Set a read timeout on the `TcpStream` using [`set_read_timeout`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.set_read_timeout). This avoids a hanging client in case the server has stopped sending but left the connection open.
  • 2. Read from the stream in a loop, using a [`BufReader`](https://doc.rust-lang.org/std/io/struct.BufReader.html), and aggregate the read bytes.
  • 3. Break out of the loop in case the read timed out or the server closed the connection.
  • Here's some example code:
  • use std::{
  • io::{self, BufReader, LineWriter, Read, Write},
  • net::TcpStream,
  • time::Duration,
  • };
  • fn main() -> io::Result<()> {
  • println!("Start of program");
  • // This is just to get data via TCP, we could of course parse the HTTP header for
  • // the message length
  • let server_host = "www.neverssl.com";
  • let server_port = "80";
  • let stream = TcpStream::connect(server_host.to_string() + ":" + server_port)?;
  • let mut reader = BufReader::new(&stream);
  • let mut writer = LineWriter::new(&stream);
  • // Don't block indefinitely on `reader.read` when there's no data to read
  • let max_read_time = Duration::from_millis(200);
  • stream.set_read_timeout(Some(max_read_time))?;
  • writer.write_all(format!("GET / HTTP/1.1\r\nhost: {server_host}\r\n\r\n").as_bytes())?;
  • let mut total_bytes_read = vec![];
  • let bytes_to_read_per_attempt = 1024;
  • let mut read_attempt_nr = 0;
  • loop {
  • read_attempt_nr += 1;
  • println!("Read attempt nr {read_attempt_nr}");
  • let mut cur_buffer = vec![0; bytes_to_read_per_attempt];
  • // If the reader has no data but the server hasn't closed the connection,
  • // by default `reader.read()` would block until the server closes the connection.
  • // Hence, we need `stream.set_read_timeout`.
  • let nr_of_bytes_read = match reader.read(&mut cur_buffer) {
  • Ok(nr_of_bytes_read) => nr_of_bytes_read,
  • Err(err) => {
  • if err.kind() == io::ErrorKind::WouldBlock || err.kind() == io::ErrorKind::TimedOut
  • {
  • println!("Read attempt timed out");
  • break;
  • } else {
  • return Err(err);
  • }
  • }
  • };
  • // Reading zero bytes indicates that the server closed the connection
  • if nr_of_bytes_read == 0 {
  • println!("Read zero bytes → Connection seems closed");
  • break;
  • }
  • // Remove the excess null bytes at the end of cur_buffer
  • cur_buffer.truncate(nr_of_bytes_read);
  • total_bytes_read.append(&mut cur_buffer);
  • println!("Read {nr_of_bytes_read} bytes in attempt nr {read_attempt_nr}");
  • }
  • let response = String::from_utf8_lossy(&total_bytes_read).to_string();
  • let nr_of_bytes_received = total_bytes_read.len();
  • println!("Server response : {response}");
  • println!("{nr_of_bytes_received} bytes received");
  • Ok(println!("End of program"))
  • }
  • This client assumes that if it hasn't received data from the server for 200 milliseconds (while the connection is still open), that the server's message is complete.
#3: Post edited by user avatar Matthias Braun‭ · 2023-04-30T12:00:24Z (12 months ago)
add explanations
  • One way to do this, is by setting a read timeout on the `TcpStream` using [`set_read_timeout`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.set_read_timeout).
  • Here's some example code:
  • use std::{
  • io::{self, BufReader, LineWriter, Read, Write},
  • net::TcpStream,
  • time::Duration,
  • };
  • fn main() -> io::Result<()> {
  • println!("Start of program");
  • // This is just to get data via TCP, we could of course parse the HTTP header for
  • // the message length
  • let server_host = "www.neverssl.com";
  • let server_port = "80";
  • let stream = TcpStream::connect(server_host.to_string() + ":" + server_port)?;
  • let mut reader = BufReader::new(&stream);
  • let mut writer = LineWriter::new(&stream);
  • // Don't block indefinitely on `reader.read` when there's no data to read
  • let max_read_time = Duration::from_millis(200);
  • stream.set_read_timeout(Some(max_read_time))?;
  • writer.write_all(format!("GET / HTTP/1.1\r\nhost: {server_host}\r\n\r\n").as_bytes())?;
  • let mut total_bytes_read = vec![];
  • let bytes_to_read_per_attempt = 1024;
  • let mut read_attempt_nr = 0;
  • loop {
  • read_attempt_nr += 1;
  • println!("Read attempt nr {read_attempt_nr}");
  • let mut cur_buffer = vec![0; bytes_to_read_per_attempt];
  • // If the reader has no data but the server hasn't closed the connection,
  • // by default `reader.read()` would block until the server closes the connection.
  • // Hence, we need `stream.set_read_timeout`.
  • let nr_of_bytes_read = match reader.read(&mut cur_buffer) {
  • Ok(nr_of_bytes_read) => nr_of_bytes_read,
  • Err(err) => {
  • if err.kind() == io::ErrorKind::WouldBlock || err.kind() == io::ErrorKind::TimedOut
  • {
  • println!("Read attempt timed out");
  • break;
  • } else {
  • return Err(err);
  • }
  • }
  • };
  • // Reading zero bytes indicates that the server closed the connection.
  • if nr_of_bytes_read == 0 {
  • println!("Read zero bytes → Connection seems closed");
  • break;
  • }
  • // Remove the excess null bytes at the end of cur_buffer
  • cur_buffer.truncate(nr_of_bytes_read);
  • total_bytes_read.append(&mut cur_buffer);
  • println!("Read {nr_of_bytes_read} bytes in attempt nr {read_attempt_nr}");
  • }
  • let response = String::from_utf8_lossy(&total_bytes_read).to_string();
  • let nr_of_bytes_received = total_bytes_read.len();
  • println!("Server response : {response}");
  • println!("{nr_of_bytes_received} bytes received");
  • Ok(println!("End of program"))
  • }
  • One way to do this, is:
  • 1. Set a read timeout on the `TcpStream` using [`set_read_timeout`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.set_read_timeout). This avoids a hanging client in case the server has stopped sending but left the connection open.
  • 2. Read from the stream in a loop, using a [`BufReader`](https://doc.rust-lang.org/std/io/struct.BufReader.html), and aggregate the read bytes.
  • 3. Break out of the loop in case the read timed out or the server closed the connection.
  • Here's some example code:
  • use std::{
  • io::{self, BufReader, LineWriter, Read, Write},
  • net::TcpStream,
  • time::Duration,
  • };
  • fn main() -> io::Result<()> {
  • println!("Start of program");
  • // This is just to get data via TCP, we could of course parse the HTTP header for
  • // the message length
  • let server_host = "www.neverssl.com";
  • let server_port = "80";
  • let stream = TcpStream::connect(server_host.to_string() + ":" + server_port)?;
  • let mut reader = BufReader::new(&stream);
  • let mut writer = LineWriter::new(&stream);
  • // Don't block indefinitely on `reader.read` when there's no data to read
  • let max_read_time = Duration::from_millis(200);
  • stream.set_read_timeout(Some(max_read_time))?;
  • writer.write_all(format!("GET / HTTP/1.1\r\nhost: {server_host}\r\n\r\n").as_bytes())?;
  • let mut total_bytes_read = vec![];
  • let bytes_to_read_per_attempt = 1024;
  • let mut read_attempt_nr = 0;
  • loop {
  • read_attempt_nr += 1;
  • println!("Read attempt nr {read_attempt_nr}");
  • let mut cur_buffer = vec![0; bytes_to_read_per_attempt];
  • // If the reader has no data but the server hasn't closed the connection,
  • // by default `reader.read()` would block until the server closes the connection.
  • // Hence, we need `stream.set_read_timeout`.
  • let nr_of_bytes_read = match reader.read(&mut cur_buffer) {
  • Ok(nr_of_bytes_read) => nr_of_bytes_read,
  • Err(err) => {
  • if err.kind() == io::ErrorKind::WouldBlock || err.kind() == io::ErrorKind::TimedOut
  • {
  • println!("Read attempt timed out");
  • break;
  • } else {
  • return Err(err);
  • }
  • }
  • };
  • // Reading zero bytes indicates that the server closed the connection.
  • if nr_of_bytes_read == 0 {
  • println!("Read zero bytes → Connection seems closed");
  • break;
  • }
  • // Remove the excess null bytes at the end of cur_buffer
  • cur_buffer.truncate(nr_of_bytes_read);
  • total_bytes_read.append(&mut cur_buffer);
  • println!("Read {nr_of_bytes_read} bytes in attempt nr {read_attempt_nr}");
  • }
  • let response = String::from_utf8_lossy(&total_bytes_read).to_string();
  • let nr_of_bytes_received = total_bytes_read.len();
  • println!("Server response : {response}");
  • println!("{nr_of_bytes_received} bytes received");
  • Ok(println!("End of program"))
  • }
  • []()
#2: Post edited by user avatar Matthias Braun‭ · 2023-04-30T11:54:03Z (12 months ago)
move comment
  • One way to do this, is by setting a read timeout on the `TcpStream` using [`set_read_timeout`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.set_read_timeout).
  • Here's some example code:
  • use std::{
  • io::{self, BufReader, LineWriter, Read, Write},
  • net::TcpStream,
  • time::Duration,
  • };
  • fn main() -> io::Result<()> {
  • println!("Start of program");
  • // This is just to get data via TCP, we could of course parse the HTTP header for
  • // the message length
  • let server_host = "www.neverssl.com";
  • let server_port = "80";
  • let stream = TcpStream::connect(server_host.to_string() + ":" + server_port)?;
  • let mut reader = BufReader::new(&stream);
  • let mut writer = LineWriter::new(&stream);
  • // Don't block indefinitely on `reader.read` when there's no data to read
  • let max_read_time = Duration::from_millis(200);
  • stream.set_read_timeout(Some(max_read_time))?;
  • writer.write_all(format!("GET / HTTP/1.1\r\nhost: {server_host}\r\n\r\n").as_bytes())?;
  • let mut total_bytes_read = vec![];
  • let bytes_to_read_per_attempt = 1024;
  • let mut read_attempt_nr = 0;
  • loop {
  • read_attempt_nr += 1;
  • println!("Read attempt nr {read_attempt_nr}");
  • let mut cur_buffer = vec![0; bytes_to_read_per_attempt];
  • let nr_of_bytes_read = match reader.read(&mut cur_buffer) {
  • Ok(nr_of_bytes_read) => nr_of_bytes_read,
  • Err(err) => {
  • if err.kind() == io::ErrorKind::WouldBlock || err.kind() == io::ErrorKind::TimedOut
  • {
  • println!("Read attempt timed out");
  • break;
  • } else {
  • return Err(err);
  • }
  • }
  • };
  • // Reading zero bytes indicates that the server closed the connection.
  • //
  • // If the reader has no data but the server hasn't closed the connection,
  • // by default `reader.read()` would block until the server closes the connection.
  • // Hence, we need `stream.set_read_timeout`.
  • if nr_of_bytes_read == 0 {
  • println!("Read zero bytes → Connection seems closed");
  • break;
  • }
  • // Remove the excess null bytes at the end of cur_buffer
  • cur_buffer.truncate(nr_of_bytes_read);
  • total_bytes_read.append(&mut cur_buffer);
  • println!("Read {nr_of_bytes_read} bytes in attempt nr {read_attempt_nr}");
  • }
  • let response = String::from_utf8_lossy(&total_bytes_read).to_string();
  • let nr_of_bytes_received = total_bytes_read.len();
  • println!("Server response : {response}");
  • println!("{nr_of_bytes_received} bytes received");
  • Ok(println!("End of program"))
  • }
  • One way to do this, is by setting a read timeout on the `TcpStream` using [`set_read_timeout`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.set_read_timeout).
  • Here's some example code:
  • use std::{
  • io::{self, BufReader, LineWriter, Read, Write},
  • net::TcpStream,
  • time::Duration,
  • };
  • fn main() -> io::Result<()> {
  • println!("Start of program");
  • // This is just to get data via TCP, we could of course parse the HTTP header for
  • // the message length
  • let server_host = "www.neverssl.com";
  • let server_port = "80";
  • let stream = TcpStream::connect(server_host.to_string() + ":" + server_port)?;
  • let mut reader = BufReader::new(&stream);
  • let mut writer = LineWriter::new(&stream);
  • // Don't block indefinitely on `reader.read` when there's no data to read
  • let max_read_time = Duration::from_millis(200);
  • stream.set_read_timeout(Some(max_read_time))?;
  • writer.write_all(format!("GET / HTTP/1.1\r\nhost: {server_host}\r\n\r\n").as_bytes())?;
  • let mut total_bytes_read = vec![];
  • let bytes_to_read_per_attempt = 1024;
  • let mut read_attempt_nr = 0;
  • loop {
  • read_attempt_nr += 1;
  • println!("Read attempt nr {read_attempt_nr}");
  • let mut cur_buffer = vec![0; bytes_to_read_per_attempt];
  • // If the reader has no data but the server hasn't closed the connection,
  • // by default `reader.read()` would block until the server closes the connection.
  • // Hence, we need `stream.set_read_timeout`.
  • let nr_of_bytes_read = match reader.read(&mut cur_buffer) {
  • Ok(nr_of_bytes_read) => nr_of_bytes_read,
  • Err(err) => {
  • if err.kind() == io::ErrorKind::WouldBlock || err.kind() == io::ErrorKind::TimedOut
  • {
  • println!("Read attempt timed out");
  • break;
  • } else {
  • return Err(err);
  • }
  • }
  • };
  • // Reading zero bytes indicates that the server closed the connection.
  • if nr_of_bytes_read == 0 {
  • println!("Read zero bytes → Connection seems closed");
  • break;
  • }
  • // Remove the excess null bytes at the end of cur_buffer
  • cur_buffer.truncate(nr_of_bytes_read);
  • total_bytes_read.append(&mut cur_buffer);
  • println!("Read {nr_of_bytes_read} bytes in attempt nr {read_attempt_nr}");
  • }
  • let response = String::from_utf8_lossy(&total_bytes_read).to_string();
  • let nr_of_bytes_received = total_bytes_read.len();
  • println!("Server response : {response}");
  • println!("{nr_of_bytes_received} bytes received");
  • Ok(println!("End of program"))
  • }
#1: Initial revision by user avatar Matthias Braun‭ · 2023-04-30T11:51:50Z (12 months ago)
One way to do this, is by setting a read timeout on the `TcpStream` using [`set_read_timeout`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.set_read_timeout).

Here's some example code:

    use std::{
        io::{self, BufReader, LineWriter, Read, Write},
        net::TcpStream,
        time::Duration,
    };

    fn main() -> io::Result<()> {
        println!("Start of program");

        // This is just to get data via TCP, we could of course parse the HTTP header for
        // the message length
        let server_host = "www.neverssl.com";
        let server_port = "80";

        let stream = TcpStream::connect(server_host.to_string() + ":" + server_port)?;

        let mut reader = BufReader::new(&stream);
        let mut writer = LineWriter::new(&stream);

        // Don't block indefinitely on `reader.read` when there's no data to read
        let max_read_time = Duration::from_millis(200);
        stream.set_read_timeout(Some(max_read_time))?;

        writer.write_all(format!("GET / HTTP/1.1\r\nhost: {server_host}\r\n\r\n").as_bytes())?;

        let mut total_bytes_read = vec![];
        let bytes_to_read_per_attempt = 1024;
        let mut read_attempt_nr = 0;
        loop {
            read_attempt_nr += 1;
            println!("Read attempt nr {read_attempt_nr}");
            let mut cur_buffer = vec![0; bytes_to_read_per_attempt];

            let nr_of_bytes_read = match reader.read(&mut cur_buffer) {
                Ok(nr_of_bytes_read) => nr_of_bytes_read,
                Err(err) => {
                    if err.kind() == io::ErrorKind::WouldBlock || err.kind() == io::ErrorKind::TimedOut
                    {
                        println!("Read attempt timed out");
                        break;
                    } else {
                        return Err(err);
                    }
                }
            };

            // Reading zero bytes indicates that the server closed the connection.
            //
            // If the reader has no data but the server hasn't closed the connection,
            // by default `reader.read()` would block until the server closes the connection.
            // Hence, we need `stream.set_read_timeout`.
            if nr_of_bytes_read == 0 {
                println!("Read zero bytes → Connection seems closed");
                break;
            }

            // Remove the excess null bytes at the end of cur_buffer
            cur_buffer.truncate(nr_of_bytes_read);
            total_bytes_read.append(&mut cur_buffer);

            println!("Read {nr_of_bytes_read} bytes in attempt nr {read_attempt_nr}");
        }
        let response = String::from_utf8_lossy(&total_bytes_read).to_string();
        let nr_of_bytes_received = total_bytes_read.len();

        println!("Server response : {response}");
        println!("{nr_of_bytes_received} bytes received");

        Ok(println!("End of program"))
    }