Jiangqiu Shen
Jiangqiu Shen

Reputation: 91

Simple Rust TcpStream client and server problem where client crash with "peer reset"

This server tries to send data to the client and the client tries to receive all the data. when a certain amount of data have been sent/received, the application exit.

the client code:

 use std::{env::args, io::Read, net::TcpStream, time::Instant};
fn main() {
    let addr = args()
        .nth(1)
        .unwrap_or_else(|| "localhost:2233".to_string());
    let size_m = args().nth(2).unwrap_or_else(|| "10".to_string());
    let size_m = size_m.parse::<usize>().unwrap();

    let mut stream = TcpStream::connect(addr.clone()).unwrap();
    println!(
        "Connected to {}, local address: {}",
        addr,
        stream.local_addr().unwrap()
    );
    let now = Instant::now();
    let mut buffer = vec![0; 1024 * 1024];
    for i in 0..size_m {
        stream.read_exact(buffer.as_mut_slice()).unwrap();
        println!("read {}MB", i + 1);
        println!(
            "average speed: {}MB/s",
            (i + 1) as f64 / now.elapsed().as_secs_f64()
        );
    }
    println!("total time: {} s", now.elapsed().as_secs_f64());
    println!(
        "speed: {} MB/s",
        size_m as f64 / now.elapsed().as_secs_f64()
    );
}

the server code:

use std::env::args;
use std::io::Write;
use std::net::TcpListener;

fn main() {
    let addr = args().nth(1).unwrap_or_else(|| ":::2233".to_string());
    let size_m = args().nth(2).unwrap_or_else(|| "10".to_string());
    let size_m = size_m.parse::<usize>().unwrap();
    let listener = TcpListener::bind(addr).unwrap();
    println!("Listening on {}", listener.local_addr().unwrap());
    if let Ok((mut stream, addr)) = listener.accept() {
        println!("Accepted connection from {}", addr);
        // create 1M buffer
        let buffer = vec![0; 1024 * 1024];
        for i in 0..size_m {
            stream.write_all(buffer.as_slice()).unwrap();
            println!("write {}MB", i + 1);
        }
        stream.flush().unwrap();
        //close stream
        // stream.shutdown(std::net::Shutdown::Both).unwrap();
    }
}


and I ran server like : cargo run --bin speedtestserver :::2233 2 client like: cargo run --bin speedtestclient ::1:2233 2

It can succeed in the same machine, but when to deploy to two different machines, the client says: "failed to fill whole buffer" or "peer reset".

Upvotes: 0

Views: 386

Answers (1)

Jiangqiu Shen
Jiangqiu Shen

Reputation: 91

Ok, I found the problem, it's about the docker container. I ran the server in a docker container using docker --rm ..., when the program finished, the docker shut down the container, and the packets failed to get out I guess. When I ran the server on the host machine, the error disappeared.

Upvotes: 1

Related Questions