1

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user3746744
  • 433
  • 1
  • 4
  • 10

1 Answers1

4

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).

Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Can you elaborate on the `Connection:close`? I cannot seem to find any reference to it. Is it part of the standard library? – rapidclock Dec 21 '19 at 07:47
  • 1
    Edit: nvm - I understand that `Connection : close` is the header included in the request for HTTP 1.1 to avoid(turn off) persistent connections. – rapidclock Dec 21 '19 at 07:54