Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Last active August 12, 2025 11:53
Show Gist options
  • Select an option

  • Save RandyMcMillan/8224f5ce34421887d1b5b012e62d20cd to your computer and use it in GitHub Desktop.

Select an option

Save RandyMcMillan/8224f5ce34421887d1b5b012e62d20cd to your computer and use it in GitHub Desktop.
tokio_read_write.rs
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
println!("Echo server listening on 127.0.0.1:8080");
loop {
let (mut socket, addr) = listener.accept().await?;
println!("Accepted connection from: {}", addr);
tokio::spawn(async move {
let mut buf = vec![0; 1024];
loop {
match socket.read(&mut buf).await {
// Return value of `Ok(0)` signifies that the remote has closed
Ok(0) => return,
Ok(n) => {
// Write the data back
if socket.write_all(&buf[..n]).await.is_err() {
// We probably encountered a broken pipe.
break;
}
}
Err(e) => {
eprintln!("failed to read from socket; err = {:?}", e);
return;
}
}
}
});
}
}
@RandyMcMillan
Copy link
Author

RandyMcMillan commented Aug 12, 2025

@RandyMcMillan
Copy link
Author

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