Skip to content

Instantly share code, notes, and snippets.

@listochkin
Created June 9, 2023 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save listochkin/bea0b4dc4ed49e629ba4930ccc023cac to your computer and use it in GitHub Desktop.
Save listochkin/bea0b4dc4ed49e629ba4930ccc023cac to your computer and use it in GitHub Desktop.
Exercise: an interactive TCP echo server

Implement an interactive TCP echo server.

Here's how an interaction with it would look like from a client point of view. You connect to it using netcat, for example:

nc localhost 7878

and type in one line of text. As soon as you hit enter, the server sends the line back but keeps the connection opened. You can type another line and get it back, and so on.

Here's a bit of code to get you started:

use std::{io, net::{TcpListener, TcpStream}};

fn handle_client(mut stream: TcpStream) -> Result<(), io::Error> {
    todo!("read stream line by line, write lines back to the stream");
    // for line in stream {
    //   write line to stream
    // }
    Ok(())
}

fn main() -> Result<(), io::Error> {
    let listener = TcpListener::bind("0.0.0.0:7878")?;
    for stream in listener.incoming() {
        let stream = stream?;
        handle_client(stream)?;
    }
    Ok(())
}

This exercise will require you to do some digging through standard library and getting acquainted with some traits and types that exist in there. The read_to_string method that you may stumble upon will only give you text after the connection is closed by the client. So, while you can use it to make an echo server it won't be interactive.

If you get stuck, you can find hints in Rust by Example. Remember: in Rust the answer is often starts with "there's a trait".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment