Sockets 什么会导致生锈';s TcpSocket::write()返回;无效输入“;?
我想在Rust中发出一个简单的HTTP请求。我把它放在一起,效果很好:Sockets 什么会导致生锈';s TcpSocket::write()返回;无效输入“;?,sockets,rust,Sockets,Rust,我想在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();
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);
}
套接字返回“无效输入”:
“无效输入”
错误不是来自套接字。它来自String
。如果read\u to\u string()
调用更改为read\u to\u 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响应是错误的。查看网页,错误在这里(代码�代码>字符是问题的关键):
有问题的字符是0x96,实际上是无效的utf-8。应该是U+2013——
该文档为iso-8859-1或windows 1252。该HTML还存在许多其他问题,例如unscaped&'s
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)
Lang.Next'14 Keynote: What � if anything � have we learned from C++?