4

使用 MIO (0.3.5) 时如何检测连接的终止?

我尝试了以下方法:

extern crate mio;
use mio::{EventLoop,Token,ReadHint};
use std::io::Read;

fn main(){
  let listener = mio::tcp::TcpListener::bind("localhost:1234").unwrap();
  let (stream,_) : (mio::tcp::TcpStream, _)  =  listener.accept().unwrap();

  let mut event_loop = EventLoop::new().unwrap();
  event_loop.register(&stream,Token(0)).unwrap();
  println!("run...");
  event_loop.run(&mut H{stream:stream}).unwrap();
}

struct H{stream : mio::tcp::TcpStream}

impl mio::Handler for H{
  type Timeout = ();
  type Message = ();

  fn readable(&mut self, _ : &mut EventLoop<Self>, _ : Token, hint: ReadHint){
    let mut buf: [u8; 500] = [0; 500];
    println!("{} {}",(hint==ReadHint::data()),self.stream.read(&mut buf).unwrap());
    std::thread::sleep_ms(1000);
  }
}

运行这个。使用类似的东西连接到它nc localhost 1234。使用 Ctrl-C 终止连接。我的代码会认为有新数据可用(hint==ReadHint::data())。尝试读取它将导致零字节可用。

提示不应该是这样的ReadHint::hup()吗?

4

1 回答 1

5

调用registermio v0.3.5 时的默认设置是仅注册readable Interest,因此这是您将获得的唯一提示。

如果您还想收到 hup 警告,则需要使用函数register_opt并将InterestandPollOpt作为参数,因此您的代码变为:

extern crate mio;
use mio::{EventLoop,Token,ReadHint,PollOpt,Interest};
use std::io::Read;

fn main() {
    let listener = mio::tcp::TcpListener::bind("localhost:1234").unwrap();
    let (stream,_) : (mio::tcp::TcpStream, _)  =  listener.accept().unwrap();

    let mut event_loop = EventLoop::new().unwrap();
    let interest = Interest::readable() | Interest::hup();
    event_loop.register_opt(&stream,Token(0), interest,PollOpt::level()).unwrap();
    println!("run...");
    event_loop.run(&mut H{stream:stream}).unwrap();
}

struct H{stream : mio::tcp::TcpStream}

impl mio::Handler for H {
    type Timeout = ();
    type Message = ();

    fn readable(&mut self, event_loop : &mut EventLoop<Self>, _ : Token, hint: ReadHint){
        let mut buf: [u8; 500] = [0; 500];
        if hint.is_hup() {
            println!("Recieved hup, exiting");
            event_loop.shutdown();
            return;
        }
        println!("{} {}",hint.is_data(),self.stream.read(&mut buf).unwrap());
        std::thread::sleep_ms(1000);
    }
}

我认为便利功能的默认值register在 v0.4.0 中已更改为,Interest::all()因此这在未来不应该成为问题。

于 2015-06-10T18:31:06.573 回答