我试着用时雄(tokio={version="1", features=["full"]}
)实现一个简单的http服务器。代码如下。奇怪的是服务器可以接收浏览器的请求,但是浏览器不能接收服务器的响应。我的代码中有什么bug吗?
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;
});
}
}
1条答案
按热度按时间xlpyo6sf1#
在状态行和实体主体之间需要一个额外的行分隔符。当response_str像这样时浏览器可以粘贴响应