gpt4 book ai didi

sockets - 什么会导致 Rust Tcp Socket::write() 返回 "invalid input"?

转载 作者:行者123 更新时间:2023-11-29 07:46:24 24 4
gpt4 key购买 nike

For a little fun我想用 Rust 发出一个简单的 HTTP 请求。我把它放在一起,效果很好:

use std::io::TcpStream;

fn main() {
// This just does a "GET /" to www.stroustrup.com
println!("Establishing connection...");
let mut stream = TcpStream::connect("www.stroustrup.com:80").unwrap();

println!("Writing HTTP request...");
// unwrap() the result to make sure it succeeded, at least
let _ = stream.write(b"GET / HTTP/1.1\r\n\
Host: www.stroustrup.com\r\n\
Accept: */*\r\n\
Connection: close\r\n\r\n").unwrap();

println!("Reading response...");
let response = stream.read_to_string().unwrap();

println!("Printing response:");
println!("{}", response);
}

响应是:

Establishing connection...
Writing HTTP request...
Reading response...
Printing response:
HTTP/1.1 200 OK
...and the rest of the long HTTP response with all the HTML as I'd expect...

但是,如果我将请求更改为 /C++.html 而不是 /:

use std::io::TcpStream;

fn main() {
// The only change is to "GET /C++.html" instead of "GET /"
println!("Establishing connection...");
let mut stream = TcpStream::connect("www.stroustrup.com:80").unwrap();

println!("Writing HTTP request...");
// unwrap() the result to make sure it succeeded, at least
let _ = stream.write(b"GET /C++.html HTTP/1.1\r\n\
Host: www.stroustrup.com\r\n\
Accept: */*\r\n\
Connection: close\r\n\r\n").unwrap();

println!("Reading response...");
let response = stream.read_to_string().unwrap();

println!("Printing response:");
println!("{}", response);
}

套接字返回“无效输入”:

Establishing connection...
Writing HTTP request...
Reading response...
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: invalid input', /Users/rustbuild/src/rust-buildbot/slave/nightly-dist-rustc-mac/build/src/libcore/result.rs:746

为什么套接字返回“无效输入”? TCP 套接字不知道 HTTP 协议(protocol)(​​我已经用 telnet 和 netcat 测试了我的请求:它是正确的),所以它不能提示 HTTP 请求/响应。

"invalid input" 在这里是什么意思?为什么这行不通?

我的 Rust 版本(我在 OS X 10.10.1 上):

$ rustc --version
rustc 1.0.0-nightly (ea6f65c5f 2015-01-06 19:47:08 +0000)

最佳答案

“无效输入” 错误不是来自套接字。它来自 String。如果 read_to_string() 调用更改为 read_to_end(),则响应成功。显然响应不是有效的 UTF-8。

更明确地说,代码:

println!("Reading response...");
let response = stream.read_to_end().unwrap();

println!("Printing response:");
println!("{}", String::from_utf8(response));

返回:

Err(invalid utf-8: invalid byte at index 14787)

所以 HTTP 响应是错误的。查看网页,错误在这里(字符是问题所在):

Lang.Next'14 Keynote: What � if anything � have we learned from C++?

关于sockets - 什么会导致 Rust Tcp Socket::write() 返回 "invalid input"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27844778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com