mirror of
https://github.com/guilhermewerner/mini-redis
synced 2025-06-16 06:55:01 +00:00
Implement Some Tokio Tutorials
This commit is contained in:
38
Tutorial/Echo.rs
Normal file
38
Tutorial/Echo.rs
Normal file
@ -0,0 +1,38 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> io::Result<()> {
|
||||
let mut listener = TcpListener::bind("127.0.0.1:6142").await.unwrap();
|
||||
|
||||
loop {
|
||||
let (mut socket, _) = listener.accept().await?;
|
||||
|
||||
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) => {
|
||||
// Copy the data back to socket
|
||||
if socket.write_all(&buf[..n]).await.is_err() {
|
||||
// Unexpected socket error. There isn't much we can
|
||||
// do here so just stop processing.
|
||||
return;
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
// Unexpected socket error. There isn't much we can do
|
||||
// here so just stop processing.
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user