"Connection reset by peer" when reading to heap memory with TcpStream

This code here works without any problem, fine:

use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:9999").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();
        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 512];
    stream.read(&mut buffer).unwrap();
    println!("{}", String::from_utf8_lossy(&buffer[..]));
}

This is written with using stack memory that has a fixed size of allocated memory, but I want to allocate
dynamic memory (perhaps more memory) for my program. So basically, I replaced let mut buffer = [0; 512]; with let mut buffer = Vec::new(); But it resets the connection when it does read.

If you want to create a simple reproducible example in your machine, execute nc 127.0.0.1 9999 command and send anything to the server.

using a Vec like this, it's initial length is 0, so that's how many bytes you will read. You should use read_to_end for unbounded memory or use a bigger buffer size like let mut buffer = vec![0;8196];

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.