在Rust中与websockets共享可变状态



我正在使用actix-web运行一个web服务器,并希望能够通过websocket消息改变状态。

我目前使用websockets的方式是通过实现actix::StreamHandler的handle方法。然而,这限制了我向它传递数据的能力。我怎么能访问数据(actix_web::web:: data)在我的句柄方法?

我能想到的解决这个问题的唯一方法是以某种方式覆盖handle的函数签名,但这似乎是不可能的

这是一些重要的代码片段,我们在app_data中有app_namenonces:

// main.rs
let nonces = Arc::new(Mutex::new(nonces::Nonces::new()));
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(app_data::AppData {
app_name: String::from("Actix Web"),
nonces: Arc::clone(&nonces),
}))
...
// app_data.rs
pub struct AppData {
pub app_name: String,
pub nonces: Arc<Mutex<nonces::Nonces>>,
}
// ws.rs
struct Ws {
app_data: web::Data<app_data::AppData>,
}
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for Ws {
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
let app_name = &self.app_data.app_name;
let mut nonces = self.app_data.nonces.lock().unwrap();
println!(">>> {app_name}");
println!(">>> {:?}", nonces.nonces);  // I have a nonces data in nonces
...
}
}
async fn index(
req: HttpRequest, 
stream: web::Payload, 
app_data: web::Data<app_data::AppData>,
) -> Result<HttpResponse, Error> {
ws::start(Ws { app_data: app_data.clone() }, &req, stream)
}

最新更新