ํƒœ์Šคํฌ

Rust์˜ ํƒœ์Šคํฌ(์ž‘์—…) ์‹œ์Šคํ…œ์€ ๊ฒฝ๋Ÿ‰ ์Šค๋ ˆ๋”ฉ์˜ ํ•œ ์ข…๋ฅ˜๋กœ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

ํ•˜๋‚˜์˜ ์ž‘์—…์—๋Š”, ์‹คํ–‰์ž๊ฐ€ ์ด ์ž‘์—…์„ ์ง„ํ–‰ํ•˜๊ธฐ ์œ„ํ•ด ๊ณ„์† ํด๋งํ•˜๋Š”, ์ตœ์ƒ์œ„ future๊ฐ€ ํ•œ ๊ฐœ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด future์—๋Š” poll ๋ฉ”์„œ๋“œ๊ฐ€ ํด๋งํ•˜๋Š” ์ค‘์ฒฉ๋œ future๊ฐ€ ํ•œ ๊ฐœ ์ด์ƒ ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ์ค‘์ฒฉ๋œ future๋Š” ์ผ๋ฐ˜์ ์ธ ํ•จ์ˆ˜ ํ˜ธ์ถœ ์Šคํƒํ•˜๊ณ  ๋น„์Šทํ•œ ์—ญํ• ์„ ํ•ฉ๋‹ˆ๋‹ค. ํ•œ ์ž‘์—… ์•ˆ์—์„œ ์—ฌ๋Ÿฌ ์ž์‹ future๋“ค์„ ํด๋งํ•˜๋ฉด, ํƒ€์ด๋จธ๋ฅผ ์ผœ๋Š” ๊ฒƒ๊ณผ ์–ด๋–ค I/O์ž‘์—…์„ ๋™์‹œ์— ์ˆ˜ํ–‰์‹œํ‚จ ํ›„ ํƒ€์ด๋จธ์™€ I/O ์ค‘ ๋จผ์ € ๋๋‚˜๋Š” ๊ฒƒ์„ ๊ธฐ๋‹ค๋ฆฌ๋Š” ๊ฒƒ๊ณผ ๊ฐ™์€๋™์‹œ์„ฑ๋„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:6142").await?;
	println!("listening on port 6142");

    loop {
        let (mut socket, addr) = listener.accept().await?;

        println!("connection from {addr:?}");

        tokio::spawn(async move {
            if let Err(e) = socket.write_all(b"Who are you?\n").await {
                println!("socket error: {e:?}");
                return;
            }

            let mut buf = vec![0; 1024];
            let reply = match socket.read(&mut buf).await {
                Ok(n) => {
                    let name = std::str::from_utf8(&buf[..n]).unwrap().trim();
                    format!("Thanks for dialing in, {name}!\n")
                }
                Err(e) => {
                    println!("socket error: {e:?}");
                    return;
                }
            };

            if let Err(e) = socket.write_all(reply.as_bytes()).await {
                println!("socket error: {e:?}");
            }
        });
    }
}

์ด ์˜ˆ์ œ๋ฅผ, ๋กœ์ปฌ ์ปดํ“จํ„ฐ์— ๋งŒ๋“ค์–ด ๋‘” src/main.rs์— ๋ณต์‚ฌํ•˜๊ณ  ๊ฑฐ๊ธฐ์—์„œ ์‹คํ–‰ํ•˜์„ธ์š”.

  • ์ˆ˜๊ฐ•์ƒ๋“ค์—๊ฒŒ ์ด ์„œ๋ฒ„์— ๋ช‡ ๊ฐœ์˜ ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์—ฐ๊ฒฐ๋˜๋ฉด ์ด ์„œ๋ฒ„์˜ ์ƒํƒœ๊ฐ€ ์–ด๋–ป๊ฒŒ ๋ณ€ํ• ์ง€ ๊ทธ๋ฆผ์„ ๊ทธ๋ ค๋ณด๋„๋ก ํ•˜์„ธ์š”. ์–ด๋–ค ํƒœ์Šคํฌ๋“ค์ด ์žˆ๋Š”์ง€, ์ด ํƒœ์Šคํฌ๋“ค์˜ Future๋Š” ์–ด๋–ค ์ƒํƒœ์— ์žˆ๋Š”์ง€ ๋ฌผ์–ด๋ด…๋‹ˆ๋‹ค.

  • async ๋ธ”๋ก์„ ์ฒ˜์Œ ๋ณด๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ํด๋กœ์ €์™€ ๋น„์Šทํ•˜์ง€๋งŒ ์ธ์ž๋ฅผ ๋ฐ›์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋ฆฌํ„ด ํƒ€์ž…์€ async fn๊ณผ ๋น„์Šทํ•œ Future์ž…๋‹ˆ๋‹ค.

  • Async ๋ธ”๋ก์„ ํ•จ์ˆ˜๋กœ ๋ฆฌํŒฉํ„ฐ๋งํ•˜๊ณ  ?๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ๋ฅผ ๊ฐœ์„ ํ•ด ๋ด…์‹œ๋‹ค.