<예제 코드_1>
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0; 1024];
// In a loop, read data from the socket and write the data back.
loop {
let n = match socket.read(&mut buf).await {
// socket closed
Ok(n) if n == 0 => return,
Ok(n) => n,
Err(e) => {
eprintln!("failed to read from socket; err = {:?}", e);
return;
}
};
// Write the data back
if let Err(e) = socket.write_all(&buf[0..n]).await {
eprintln!("failed to write to socket; err = {:?}", e);
return;
}
}
});
}
}
<예제 코드_2>
use std::ops::{Add, AddAssign};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
#[tokio::main]
async fn main() {
let value = Arc::new(RwLock::new(1));
let value_copy = value.clone();
tokio::spawn(async move {
let read_lock = value_copy.read().await;
println!("This is the value: {:?}", read_lock);
});
tokio::time::sleep(Duration::from_secs(1)).await;
tokio::spawn(async move {
let mut write_lock = value.write().await;
write_lock.add_assign(1);
println!("This is the value after write: {:?}", write_lock);
});
tokio::time::sleep(Duration::from_secs(1)).await;
}
<참조 1> https://docs.rs/tokio/latest/tokio/
<참조 2> https://velog.io/@pandawithcat/Rust-Tokio%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0
'Rust' 카테고리의 다른 글
[Rust] Web Crawler 예제 (55일차) (0) | 2023.02.08 |
---|---|
[Rust] Derive 예제 (54일차) (0) | 2023.02.07 |
[Rust] HashMap 예제 (52일차) (0) | 2023.02.03 |
[Rust] Overloading 예제 (51일차) (0) | 2023.02.02 |
댓글