0

I'm trying to write a small webserver that returns delayed responses using the Tokio library. I've been reading the documentation of the 0.2.0-alpha.6 release and the current example of an echo server.

I modified it like this:

use std::net::SocketAddr;
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::prelude::*;
use tokio::timer::delay_for;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr = "127.0.0.1:8080".parse::<SocketAddr>()?;
    let mut listener = TcpListener::bind(&addr).await?;

    loop {
        let (mut socket, _) = listener.accept().await?;

        tokio::spawn(async move {    
            delay_for(Duration::from_millis(5000)).await;

            if let Err(e) = socket
                .write_all(b"HTTP/1.1 200 OK\r\n\r\nyay\r\n\r\n")
                .await
            {
                println!("failed to write to socket; err = {:?}", e);
            }
        });
    }
}

This code waits for 5 seconds before returning "yay" with status code 200. When I open a couple of tabs in the browser and refresh them all at once, I would expect them all to complete at roughly the same time. But in reality, the tabs complete their requests sequentially.

What can I do to make these requests run in parallel?

fafl
  • 7,222
  • 3
  • 27
  • 50
  • 1
    have you test with something more robust than browser ? like curl ? – Stargateur Nov 20 '19 at 17:50
  • What do you believe your `loop` to be doing? Why is there any reading at all in this example? Does the problem continue to manifest if you don't read? Ideally, you'd produce a [MRE] to narrow down the problem. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster Nov 20 '19 at 17:50
  • Your code works fine and serves requests in parallel: `for i in $(seq 10) ; do time curl -vvvvvv http://127.0.0.1:8080 &; done` ... each response takes ~5 seconds. – Shepmaster Nov 20 '19 at 17:58
  • It looks like your question might be answered by the answers of [Chrome stalls when making multiple requests to same resource?](https://stackoverflow.com/q/27513994/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Nov 20 '19 at 18:14
  • 1
    @Shepmaster ah, so it was Chrome! I’ve been going crazy over here. Thank you for finding this! If you make this an answer then I will accept it. – fafl Nov 20 '19 at 18:24

0 Answers0