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.

Read all data from TCP stream in Rust

+5
−1

I'd like to write a TCP client in Rust that can receive the entire message sent by a server, but I have no information about the length of a message.

I'm aware that TCP doesn't preserve message boundaries.

Still, what's the best I can do to read the entire message from the TcpStream?

In the scenario the client should work, there's no protocol for the messages sent from server to client: The client doesn't know beforehand how many bytes are in a message and the message doesn't have a header (as in HTTP) that would contain the message length. There's no special delimiter that marks the end of a message.

Also, the server might keep the TCP connection open after sending a message, meaning I can not rely on every message being completed with a server FIN.

I'd like to do this using Rust's standard library only, no other dependencies.

History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

There's nothing you can do. It's impossible. Setting a timeout doesn't guarantee the received data i... (5 comments)

1 answer

+2
−2

One way to do this, is:

  1. 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.
  2. Read from the stream in a loop, using a BufReader, 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.

History
Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »