使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
运行这个.使用类似的东西连接到它nc localhost 1234.使用Ctrl-C终止连接.我的代码会认为有新数据可用(hint==ReadHint::data()).尝试读取它将导致零字节可用.
暗示不应该是这样的ReadHint::hup()吗?
调用registermio v0.3.5 时的默认设置是仅注册readable Interest,因此这是您将获得的唯一提示.
如果你想要警告hup,你需要使用函数register_opt并给你Interest和PollOpt作为参数,所以你的代码变成:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为方便功能的默认值register在v0.4.0中已经改变,Interest::all()所以这不应该是将来的问题.
| 归档时间: |
|
| 查看次数: |
729 次 |
| 最近记录: |