我希望使用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是我找到的唯一一种解决方案,它可以执行多个线程,并在生成它们之后永远等待。我认为它是有效的,但我想知道是否有更简单的解决方案。
发布于 2017-04-12 12:19:19
您可以从一个线程运行多个服务器。core.run(server).unwrap();只是一种方便的方法,并不是唯一的/main方法。
不是运行单个ForEach来完成,而是单独派生每个线程,然后只保持线程活动:
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(())
});
handle.spawn(sock);
handle.spawn(server);
loop {
core.turn(None);
}发布于 2019-05-26 08:38:00
我只想跟进一下,似乎有一种比46bit的答案更少手动的方法(至少到2019年)。
let addr1 = "127.0.0.1:80".parse().unwrap();
let addr2 = "127.0.0.1:443".parse().unwrap();
let sock1 = TcpListener::bind(&addr1, &handle).unwrap();
let sock2 = TcpListener::bind(&addr2, &handle).unwrap();
let server1 = sock1.incoming().for_each(|_| Ok(()));
let server2 = sock2.incoming().for_each(|_| Ok(()));
let mut runtime = tokio::runtime::Runtime()::new().unwrap();
runtime.spawn(server1);
runtime.spawn(server2);
runtime.shutdown_on_idle().wait().unwrap();https://stackoverflow.com/questions/42759882
复制相似问题