我尝试使用tokio(tokio={version="1", features=["full"]})实现一个简单的http服务器。代码在下面。问题是服务器可以从浏览器接收请求,但是浏览器不能接收来自服务器的响应。我的代码中有错误吗?
use tokio::{self, net};
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;
async fn process(mut stream: TcpStream) {
let mut buf = [0u8; 4096];
loop {
let n = stream.read(&mut buf).await.unwrap();
if n == 0 {
break;
}
let s = String::from_utf8_lossy(&buf[0..n]).to_string();
print!("{}", s);
if s.ends_with("\r\n\r\n") {
println!("request received");
break;
}
}
let response_str = "HTTP/1.1 200 OK
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"udf-8\">
<title>Hello!</title>
</head>
<body>
HELLO
</body>
</html>
";
println!("response");
// browser doesn't receive the response that this line of code send.
stream.write(response_str.as_bytes()).await.unwrap();
stream.flush().await.unwrap();
println!("response DONE");
}
#[tokio::main]
async fn main() {
let listener = net::TcpListener::bind("127.0.0.1:9998").await.unwrap();
loop {
let (stream, _) = listener.accept().await.unwrap();
tokio::spawn(async move{
process(stream).await;
});
}
}发布于 2022-12-02 23:33:56
在状态线和实体体之间需要一个额外的行分隔符。当response_str如下所示时,浏览器可以调整响应
let response_str = "HTTP/1.1 200 OK
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"udf-8\">
<title>Hello!</title>
</head>
<body>
HELLO
</body>
</html>"https://stackoverflow.com/questions/74662212
复制相似问题