我想这个工作需要使用select(2),但是构建C参数的fd_sets似乎很麻烦。
我认为poll(2)应该更方便。例如:
#![feature(std_misc, net, libc, os, io)]
extern crate libc;
use libc::{c_int, c_uint, c_short};
use std::thread::spawn;
use std::net::{TcpListener, TcpStream};
use std::os;
use std::io::Read;
use std::os::unix::AsRawFd;
#[repr(C)]
struct pollfd {
fd: c_int,
events: c_short,
revents: c_short,
}
extern { fn poll(fds: *mut pollfd, nfds: c_uint, timeout: c_int) -> c_int; }
const POLLIN: c_short = 1;
fn handle_client(mut stream: TcpStream) {
let mut fdset = pollfd { fd: stream.as_raw_fd(), events: POLLIN, revents: 0, };
loop {
match unsafe { poll(&mut fdset as *mut _, 1, -1) } {
ret if ret < 0 => panic!("poll error: {}", os::last_os_error()),
ret if ret > 0 && fdset.events == fdset.revents => {
let mut byte: &mut [u8] = &mut [0];
match stream.read(&mut byte).unwrap() {
0 => break,
1 => println!("A byte read: {}", byte[0]),
_ => unreachable!(),
}
},
_ => break,
}
}
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:9999").unwrap();
for stream in listener.incoming() {
match stream {
Ok(stream) => { spawn(move || handle_client(stream)); },
Err(e) => panic!("connection error: {}", e),
}
}
}