我希望使用Rust和Tokio构建多个并发服务器,这些服务器会在不同的端口上运行:
let mut core = Core::new().unwrap();
let handle = core.handle();
// I want to bind to multiple port here if it's possible with simple addresses
let addr = "127.0.0.1:80".parse().unwrap();
let addr2 = "127.0.0.1:443".parse().unwrap();
// Or here if there is a special function on the TcpListener
let sock = TcpListener::bind(&addr, &handle).unwrap();
// Or here if there is a special function on the sock
let server = sock.incoming().for_each(|(client_stream, remote_addr)| {
// And then retrieve the current port in the callback
println!("Receive connection on {}!", mysterious_function_to_retrieve_the_port);
Ok(())
});
core.run(server).unwrap();
有没有使用Tokio监听多个端口的选项,或者我需要为每个端口创建一个简单的线程,并在每个线程中运行Core::new()
?
感谢rust-scoped-pool,我现在可以:
let pool = Pool::new(2);
let mut listening_on = ["127.0.0.1:80", "127.0.0.1:443"];
pool.scoped(|scope| {
for address in &mut listening_on {
scope.execute(move ||{
let mut core = Core::new().unwrap();
let handle = core.handle();
let addr = address.parse().unwrap();
let sock = TcpListener::bind(&addr, &handle).unwrap();
let server = sock.incoming().for_each(|(client_stream, remote_addr)| {
println!("Receive connection on {}!", address);
Ok(())
});
core.run(server).unwrap();
});
}
});
rust-scoped-pool是我找到的唯一解决方案,可用于执行多个线程并在它们被生成后永久等待。我认为它起作用了,但我想知道是否存在更简单的解决方案。