Last active
June 5, 2023 22:46
-
-
Save gitmpr/9798142896d686c0ec9fa1a59dd26bda to your computer and use it in GitHub Desktop.
Echo back a string over a socket
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::net::{TcpListener, TcpStream}; | |
use tokio::io::{AsyncReadExt, AsyncWriteExt}; | |
#[tokio::main] | |
async fn main() -> Result<(), Box<dyn std::error::Error>> { | |
let listener = TcpListener::bind("0.0.0.0:8080").await?; | |
loop { | |
let (mut socket, _) = listener.accept().await?; | |
tokio::spawn(async move { | |
let mut buf = [0; 1024]; | |
loop { | |
let n = match socket.read(&mut buf).await { | |
Ok(n) if n == 0 => break, | |
Ok(n) => n, | |
Err(e) => { | |
eprintln!("failed to read from socket; err = {:?}", e); | |
break; | |
} | |
}; | |
let message = String::from_utf8_lossy(&buf[..n]).to_string(); | |
let response = format!("{}", message); | |
if let Err(e) = socket.write_all(response.as_bytes()).await { | |
eprintln!("failed to write to socket; err = {:?}", e); | |
break; | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment