TcpStream.read阻塞,如何解决呢
我是rust新手,最近在学习网络模块,遇到了这个阻塞问题。我看别人的代码都是直接调用read()方法,但是我的代码会被阻塞。现象如下:
- 运行程序
- 浏览器输入127.0.0.1:4221
- 控制台无输入,浏览器一直在转圈
最后发现是_stream.read() 再次进入时会阻塞,我想应该是EOF, 但是如何处理EOF呢,它也不报错,也不返回OK(0)?
代码如下:
// Uncomment this block to pass the first stage
use std::net::TcpListener;
use std::io::{ErrorKind, Read, Write};
fn main(){
// You can use print statements as follows for debugging, they'll be visible when running tests.
println!("Logs from your program will appear here!");
// Uncomment this block to pass the first stage
let listener = TcpListener::bind("127.0.0.1:4221").unwrap();
//listener.set_nonblocking(true).unwrap();
//
for stream in listener.incoming() {
match stream {
Ok(mut _stream) => {
println!("accepted new connection");
let mut data = String::new();
let mut buffer = [0; 2048];
loop {
_stream.set_ttl(110).unwrap();
let result = _stream.read(&mut buffer);
match result {
Ok(len)=>{
if len==0 {
println!("len==0, have read all data from stream");
break;
}
data.push_str(std::str::from_utf8(&buffer).unwrap())
},
Err(e)=>{
if e.kind() == ErrorKind::UnexpectedEof {
println!("EOF, have read all data from stream");
break;
}
}
}
}
if data.is_empty() {
println!("receive nothing ", );
}else {
//let content = String::from_utf8(all_datas).expect("error when converts String");
println!("the request content is {}", data);
let path = data.split_whitespace().nth(1).unwrap();
println!("the request path is {}", path);
let response = if "/"==path {
"HTTP/1.1 200 \r\n\r\n"
}else {
"HTTP/1.1 404 Not Found\r\n\r\n"
};
_stream.write(response.as_bytes()).expect("Response to client failed!");
_stream.flush().expect("Some errors occurs when flush");
}
}
Err(e) => {
println!("error: {}", e);
}
}
}
}
data.push_str(std::str::from_utf8(&buffer).unwrap()) 这个后面你得判断你的http协议本次是不是读完整了 读完整了就break掉