Bruce
Bruce

Reputation: 501

How to read line-by-line from a TcpStream?

I'm following the Make a simple TCP server example in the nightly docs. I've connected via telnet and I'd like to see data sent line by line. Right now I'm read_to_string and I only get data when I close the telnet connection. I'd like to be able to read each line at the server after the user in the telnet session hits enter.

Upvotes: 5

Views: 3259

Answers (1)

Bruce
Bruce

Reputation: 501

This is what I came up after reading the docs for BufferedReader.

fn handle_client(mut stream: TcpStream) {
    let wresult = stream.write_line("Welcome.");
    match wresult {
        Err(e) => {
            println!("error writing: {}", e);
        }
        _ => {}
    }
    let mut reader = BufferedReader::new(stream);

    loop {
        let result = reader.read_line();
        match result {
            Ok(data) => {
                println!("{}", data.as_slice().trim());
            }
            Err(e) => {
                println!("error reading: {}", e);
                break;
            }
        }
    }
}

Upvotes: 9

Related Questions