我正在尝试用 Rust 制作一个多线程 tcp 通信程序
这个想法是主线程上存在一个侦听套接字,并且当连接进入时,工作由工作线程处理
我之前使用了 Rust 书中找到的 ThreadPool 方法,但据我了解,tokio 能够“自动”将工作分配给池中的线程
我对操作系统线程和 tokio 任务之间的区别感到困惑(主要是因为您用来spawn创建两者)
这是一些代码
fn main() {
println!("Hello World!");
let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 103, 7)), 2048);
println!("socket -> {}", socket);
// You need to use the tokio runtime to execute async functions
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
let listener = StartListen::new(socket).await.unwrap();
});
}
Run Code Online (Sandbox Code Playgroud)
我StartListen在另一个文件中定义了
// Defines the StartListen class
pub struct StartListen {
listener: TcpListener,
}
// Implementation for …Run Code Online (Sandbox Code Playgroud)