Created
October 26, 2022 10:30
-
-
Save ssrlive/1ff6f99a4e890236991e5b6d51e2c26f to your computer and use it in GitHub Desktop.
Tokio server code.
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
| // tokio = { version = "1.21.2", features = ["full"] } | |
| use tokio::net::TcpListener; | |
| use tokio::io::{AsyncReadExt, AsyncWriteExt}; | |
| #[tokio::main] | |
| async fn main() -> anyhow::Result<()> { | |
| let listener = TcpListener::bind("127.0.0.1:6379").await?; | |
| loop { | |
| let (mut socket, _) = listener.accept().await?; | |
| tokio::spawn(async move { | |
| let mut buf = vec![0; 1024]; | |
| loop { | |
| match socket.read(&mut buf).await { | |
| Ok(n) => { | |
| println!("read {} bytes", n); | |
| if n == 0 { | |
| println!("socket closed by remote node, return"); | |
| return; | |
| } | |
| // Copy the data back to socket | |
| if let Err(e) = socket.write_all(&buf[..n]).await { | |
| println!("failed to write to socket; err = {:?}", e); | |
| return; | |
| } | |
| } | |
| Err(e) => { | |
| println!("failed to read from socket; err = {:?}", e); | |
| return; | |
| } | |
| } | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment