Feat: Echo TCP server

- Each message sent by a TCP client will be bounced back to them.
- Support multiple clients
This commit is contained in:
minhtrannhat
2022-01-19 16:09:35 -05:00
commit 287284ef0e
4 changed files with 324 additions and 0 deletions

43
src/main.rs Normal file
View File

@@ -0,0 +1,43 @@
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();
}
});
}
}