gpt4 book ai didi

concurrency - 如何使用 Rust 和 Tokio 构建多个并发服务器?

转载 作者:行者123 更新时间:2023-11-29 08:07:48 24 4
gpt4 key购买 nike

我希望使用 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 是我发现执行多个线程并在生成它们后永远等待的唯一解决方案。我认为它可行,但我想知道是否存在更简单的解决方案。

最佳答案

您可以从一个线程运行多个服务器。 core.run(server).unwrap(); 只是一种方便的方法,并不是唯一/主要的做事方式。

而不是运行单个 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);
}

关于concurrency - 如何使用 Rust 和 Tokio 构建多个并发服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42759882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com