cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
642 stars 100 forks source link

Problem about 20.3 "Listing 20-25: Shut down the server after serving two requests by exiting the loop" #199

Open muayiqi opened 4 months ago

muayiqi commented 4 months ago

my main function is :

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    let pool = ThreadPool::new(4).expect("Init thread pool failed");

    for stream in listener.incoming().take(2) {
        let stream = stream.unwrap();
        pool.execute(move || {
            handle_connection(stream);
        });
    }

    println!("Shutting down.");
}

and other codes are the same as this book, when I run the server, then use the Edge browser to access "localhost:7878" only once, I get the output:

Worker 0 got a job; executing.
Worker 1 got a job; executing.
Shutting down.
Shutting down worker 0
Worker 2 got a job; executing.
Worker 3 disconnected; shutting down.
Worker 0 disconnected; shutting down.
Worker 1 disconnected; shutting down.
Shutting down worker 1
Shutting down worker 2

I mean that one request but get two jobs, when I use: echo "hello" > /dev/tcp/127.0.0.1/7878 in Ubuntu, I get the proper output, one request, one job. I really want to know the reason, thank you~

bfedie518 commented 4 months ago

Edge is sending two requests. If you use another browser like Firefox, you'll get the behavior you expect.

If you want to see what the requests are, you could print them out like we did in the first version of handle_connection() (listing 20-2).