How do I prevent TcpStream from blocking on a read

2019-08-11 01:29发布

let listener = TcpListener::bind("localhost:1234").unwrap();
for stream in listener.incoming() {
    let s = stream.unwrap();
    handle_stream(s);
}   

fn handle_stream(mut stream: TcpStream) -> () {
    let mut buf = [0];
    loop {
        let _ = match stream.read(&mut buf) {
            Err(e) => panic!("Got an error: {}", e),
            Ok(m) => {
                println!("Received {:?}, {:?}", m, buf);
                if m == 0 {
                     // doesn't reach here.
                     break;
                }
                m
            },
        };
    }
}

I then connect to the server by running curl http://localhost:1234.

I expect Ok(0) would be returned, but it doesn't reach that statement and it hangs instead. If that's an EOF, how can I treat in this case?

标签: rust
1条回答
甜甜的少女心
2楼-- · 2019-08-11 01:38

You want to use TcpStream::set_read_timeout and then check for that specific type of error:

use std::io::{self, Read};
use std::net::{TcpListener, TcpStream};
use std::time::Duration;

fn main() {
    let listener = TcpListener::bind("localhost:1234").unwrap();
    for stream in listener.incoming() {
        let s = stream.unwrap();
        handle_stream(s);
    }

    fn handle_stream(mut stream: TcpStream) -> () {
        let mut buf = [0];
        stream.set_read_timeout(Some(Duration::from_millis(100))).unwrap();
        loop {
            let _ = match stream.read(&mut buf) {
                Err(e) => {
                    match e.kind() {
                        io::ErrorKind::WouldBlock => {
                            println!("would have blocked");
                            break;
                        },
                        _ => panic!("Got an error: {}", e),
                    }
                },
                Ok(m) => {
                    println!("Received {:?}, {:?}", m, buf);
                    if m == 0 {
                        // doesn't reach here.
                        break;
                    }
                    m
                },
            };
        }
    }
}
查看更多
登录 后发表回答