user3746744
user3746744

Reputation: 443

Why is a raw HTTP request extremely slow?

When I try to send HTTP request packets using sockets it is extremely slow. It takes about 30 seconds to get a reply whereas in any other language with the same base code it takes 1 second.

use std::old_io::BufferedStream;
use std::old_io::TcpStream;

fn main() {
    let mut reddit = BufferedStream::new(TcpStream::connect("reddit.com:80").unwrap());
    reddit.write_all(format!("GET / HTTP/1.1{0}User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 zlib/1.2.3.4 libidn/1.23 librtmp/2.3{0}Host: www.reddit.com{0}Accept: */*{0}{0}", "\r\n").as_bytes());
    reddit.flush();
    let reply = reddit.read_to_string().unwrap();
    println!("{}", reply);
}

Is this a bug in Rust?

Upvotes: 1

Views: 1135

Answers (1)

Shepmaster
Shepmaster

Reputation: 431439

It's because you are using HTTP 1.1, which allows persistent connections. 30 seconds is probably the timeout of the server on the other end.

Switch to HTTP 1.0 or properly close the connection, perhaps by using the header Connection: close. Doing either of these reduces the run time to ~170ms, without enabling any compile-time optimizations (which probably don't do much here anyway).

Upvotes: 4

Related Questions