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".