我正在使用Rust-websocket及其基于Tokio的异步系统在Rust中编写一个websocket服务器。我可以为客户提供服务,但是我无法弄清楚如何在客户之间共享可变状态。这是一些(部分)代码演示了此问题:
let mut core = Core::new().unwrap();
let handle = core.handle();
let server = Server::bind("localhost:62831", &handle).unwrap();
let mut state = State{
...
};
let f = server.incoming()
.map_err(|InvalidConnection {error, ..}| error)
.for_each(|upgrade, _)| {
let f = upgrade.accept()
.and_then(|s, _| {
let ctx = ClientContext{
// some other per-client values
state: &mut state,
}
...
return s.send(Message::binary(data).into())
.and_then(move |s| Ok(s, ctx)); // this could be the complete wrong way to insert context into the stream
}).and_then(|s, ctx| {
// client handling code here
});
handle.spawn(f
.map_err(...)
.map(...)
);
return Ok(())
});
core.run(f).unwrap();
此代码与此错误:
error[E0373]: closure may outlive the current function, but it borrows `**state`, which is owned by the current function
--> src/main.rs:111:27
|
111 | .and_then(|(s, _)| {
| ^^^^^^^^ may outlive borrowed value `**state`
...
114 | state: &mut state,
| ----- `**state` is borrowed here
|
help: to force the closure to take ownership of `**state` (and any other referenced variables), use the `move` keyword, as shown:
| .and_then(move |(s, _)| {
当尝试编译器的建议时,我得到以下信息:
error[E0507]: cannot move out of captured outer variable in an `FnMut` closure
--> src/main.rs:111:27
|
111 | .and_then(move |(s, _)| {
| ^^^^^^^^^^^^^ cannot move out of captured outer variable in an `FnMut` closure
error: `state` does not live long enough
--> src/main.rs:114:37
|
114 | state: &mut state,
| ^^^^^ does not live long enough
...
122 | })
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
我还尝试将状态包装在
RefCell
中(在状态本身之后立即创建RefCell
),但是,编译器会给出类似的移动错误,因为它尝试将RefCell
移动到创建客户端上下文的闭包中。 最佳答案
您与 RefCell
非常接近。现在,您需要的是 Rc
来包装该RefCell
,以便您可以克隆Rc
而不捕获RefCell
本身。
let shared_state = Rc::new(RefCell::new(State::new())));
incoming().for_each(move |s, _| {
let shared_state = shared_state.clone(); // Left uncaptured
shared_state.borrow_mut().do_mutable_state_stuff(); // Could panic
});
请注意,由于您现在正在使用
Rc
和RefCell
,因此可能需要继续进行并将ClientContext
结构转换为存储Rc>而不是&mut State
。也许可以继续使用&mut State
进行某些操作,但是您的&mut State
会与 RefMut
的生命周期相关联,如果在下一次闭包运行之前将其保持事件状态,则借用将发生 panic (如果失败,则失败。使用try_
变体)。还请记住,如果您决定要在 react 堆中有多个线程,则只需将
Rc
更改为 Arc
,将RefCell
更改为 Mutex
,这在需要时是非常自然的转换。关于asynchronous - 使用异步(tokio)rust-websocket在客户端之间共享可变状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44876934/