use tokio::{ io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, net::TcpListener, }; #[tokio::main] async fn main() { // Set up a TCP listenner to listen for incoming tcp requests let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap(); // First loop accept all the tcp client requests loop { // accept the requests let (mut socket, _addr) = listener.accept().await.unwrap(); tokio::spawn(async move { // Splitting the TCP socket into read/write halves let (reader, mut writer) = socket.split(); let mut buffer_reader = BufReader::new(reader); let mut line: String = String::new(); // second loop keeps receving input from that one client going loop { // number of bytes read. We will truncate the buffer let bytes_read = buffer_reader.read_line(&mut line).await.unwrap(); // If we received no bytes then the tcp socket must have closed if bytes_read == 0 { break; } // Does not write to every single tcp sockets that are connected // It only writes every single bytes in the input buffer writer.write_all(line.as_bytes()).await.unwrap(); // clear the input buffer line.clear(); } }); } }