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?