TcpListener
https://docs.rs/tokio/latest/tokio/net/struct.TcpListener.html
TcpListnerは元々Asyncにラップされているから、シングルスレッドでは使えない。
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
#[tokio::main]
async fn main() -> std::io::Result<()> {
let addr = "0.0.0.0:8080";
let listener = TcpListener::bind(addr).await?;
loop {
match listener.accept().await {
Ok((mut socket, _)) => {
let mut buf = Vec::with_capacity(4096);
socket.read_buf(&mut buf).await?;
let msg = String::from_utf8(buf).expect("failed to convert str");
println!("{msg}");
socket.write(msg.as_bytes()).await?;
}
Err(err) => {
println!("{err:?}");
}
};
}
}
Compiling parallel v0.1.0 (/home/vagrant/dev/rust/parallel)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.74s
Running `target/debug/parallel`
GET / HTTP/1.1
Host: 192.168.33.10:8080
User-Agent: curl/7.81.0
Accept: */*
ncコマンドで接続できる
$ nc 192.168.33.10 8080
hello
hello