Skip to content

Instantly share code, notes, and snippets.

@kgmyatthu
Created September 21, 2023 08:24
Show Gist options
  • Save kgmyatthu/0accfcf325844c42fec0279f4f418818 to your computer and use it in GitHub Desktop.
Save kgmyatthu/0accfcf325844c42fec0279f4f418818 to your computer and use it in GitHub Desktop.
Rust TCP echo server
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
const ECHO_SERVER_ADDRESS: &str = "127.0.0.1:1337";
#[tokio::main]
async fn main(){
let tcp_listner = TcpListener::bind(ECHO_SERVER_ADDRESS).await.unwrap();
loop {
let (socket, _) = tcp_listner.accept().await.unwrap();
tokio::spawn(async move {
handle_stream(socket).await;
});
}
}
async fn handle_stream(mut stream: TcpStream){
println!("Connected by {}", stream.peer_addr().unwrap());
let mut buffer = [0u8; 1024];
while match stream.read(&mut buffer).await {
Ok(size) => {
println!("Received: {}", String::from_utf8_lossy(&buffer[..size]));
let _ = stream.write(&buffer[..size]).await.unwrap();
true
}
Err(e) => {
println!("Error: {}", e);
false
}
} {}
}
@kgmyatthu
Copy link
Author

Tokio runtime

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