Connect `stdin` directly to stream input


#1

Hi, i’m trying to connect what comes from stdin directly into a UnixStream and what comes out of it directly to stdout.

Here’s what i’m doing currently:

let stdout = io::stdout();
let mut stdout_handle = stdout.lock();

let stdin = io::stdin();


loop {
    let mut input = String::new();
    stdin.read_line(&mut input).unwrap();

    stream.write(input.as_bytes()).unwrap();
    thread::sleep(time::Duration::from_secs(1));

    match stream.read(&mut buffer[..]) {
        Ok(n) => {
            stdout_handle.write(&buffer[0..n]).unwrap();
        },
        Err(e) => {println!("Something occured: {}", e);}
    }

}

It works but stdin.read_line(&mut input).unwrap(); blocks and i’ve to wait a bit to get the response from the UnixStream. How could I achieve this in an asynchronous fashion?


#2

Would something like stdin.bytes().peekable() help?


#3

Take a look at the tokio process crate - it’ll allow you to work with the stdin/stdout streams asynchronously.

You can also create background threads that service stdin/stderror I/O (in a blocking manner) and let the main thread orchestrate between them.