为什么原始HTTP请求极其缓慢? [英] Why is a raw HTTP request extremely slow?

查看:33
本文介绍了为什么原始HTTP请求极其缓慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用套接字发送HTTP请求数据包时,它的速度非常慢.得到回复大约需要30秒,而使用其他具有相同基本代码的语言,则需要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);
}

这是Rust中的错误吗?

Is this a bug in Rust?

推荐答案

这是因为您使用的是HTTP 1.1,允许持久连接 .30秒可能是另一端服务器的超时.

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.

切换到HTTP 1.0或正确关闭连接,也许使用标题 Connection:close .采取上述任何一种措施都可以将运行时间减少到〜170ms,而无需启用任何编译时优化(无论如何在这里做得并不多).

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

这篇关于为什么原始HTTP请求极其缓慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆