Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if data is available on TcpStream

I have a std::net::TcpStream. I want to determine if there is data available to be read without actually reading it yet.

The only relevant API I can find on TcpStream itself is read which

does not provide any guarantees about whether it blocks waiting for data

which does not sound encouraging for this problem.

A related question seems to drop down to file descriptors and read(2) to force an nonblocking read. However I cannot figure out how to use read(2) to peek at an fd without actually reading it.

I suppose this is a job for select(2), but constructing the fd_sets for the C arguments seems rather hairy. There certainly is not a Rust type for that, and it's not immediately clear how I would invent one.

like image 385
Drew Avatar asked Nov 09 '22 18:11

Drew


1 Answers

I suppose this is a job for select(2), but constructing the fd_sets for the C arguments seems rather hairy.

I suppose poll(2) should be more convenient. For example:

#![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),
        }
    }
}
like image 153
swizard Avatar answered Nov 15 '22 05:11

swizard