Tokio 'io::read_to_end' doesn't finish reading HTTP request

This is my first time working with Tokio and I am rather new to Rust itself. I am trying to build an Asynchronous I/O based web server. My first aim is to have the server receive and display any requests received in plaintext. Oddly when I make a request from my browser it doesn't stop loading. If I cancel the request the server then receives it. I have provided by code below.

extern crate tokio;

use tokio::io;
use tokio::net::{TcpListener};
use tokio::prelude::*;
use tokio::io::Error;

fn main() {

    let addr = "127.0.0.1:7878".parse().unwrap();
    let listener = TcpListener::bind(&addr)
        .expect("unable to bind TCP listener");

    let server = listener.incoming()
        .map_err(|e| eprintln!("accept failed = {:?}", e))
        .for_each(|sock| {

        let (reader, _) = sock.split();

        let incoming = vec![];
        let handle_conn = io::read_to_end(reader, incoming)
            .then(|result| {
                let result = result.unwrap();
                let data = result.1;
                println!("{}", std::str::from_utf8(&data).unwrap());
                Ok(())
            })
            .map_err(|_: Error| {});

        tokio::spawn(handle_conn)
    });

    // Start the Tokio runtime
    tokio::run(server);

}

read_to_end reads until the sender closes the socket, but due to HTTP keepalive the browser doesn't close the socket. You should use an HTTP library like hyper to handle the parsing.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.