-
-
Save RandyMcMillan/8224f5ce34421887d1b5b012e62d20cd to your computer and use it in GitHub Desktop.
tokio_read_write.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } | |
| } | |
| }); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/RandyMcMillan/8224f5ce34421887d1b5b012e62d20cd