Read from stdin, but only while socket is connected

62 Views Asked by At

I'm trying to build a simple Rust in-terminal TCP chat program. I want to read user input from stdin, but only while the connection is still alive.

Specifically I want to avoid the situation where you send a line only to notice that the connection has been broken.

How can I abort my line read in such a situation? Ideally I'd print a message and attempt to reconnect, without disrupting whatever the user has been writing so far. At the very least I want to mimic the behaviour of SSH in the way that it tells you that the connection has been lost and aborts the read.

This is as much a conceptual/design question as it is an engineering one. There are probably a few ways to solve this and I'd appreciate good suggestions on how to do this in an idiomatic way.

Currently I'm just calling this function in a loop, whereupon I transmit whatever I read:

fn read_line() -> String {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).unwrap();
    input.trim().to_string()
}
0

There are 0 best solutions below