rust 在Actix Web WebSocket间隔内调用异步函数

rta7y2nd  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(279)

我试图在Actix Web WebSocket间隔内运行异步代码,但我不知道如何做到这一点。我读过this question,但我不确定是否应该采用相同的方法来解决我的问题,因为它在设计和执行方面略有不同。下面是我的代码:

struct WebSocket {
    data: Data<State>,
    user: ID,
}

const POLL_INTERVAL: Duration = Duration::from_millis(5);

impl Actor for WebSocket {
    type Context = WebsocketContext<Self>;

    fn started(&mut self, ctx: &mut Self::Context) {
        ctx.run_interval(POLL_INTERVAL, |myself, ctx| {
            // let fut = ws_poll(myself.user, &myself.data.event_client);

            // fut.into_actor(myself).spawn(ctx);
            // I want to do async stuff in here
            // my_async_fn().await;
        });
    }
}

impl StreamHandler<Result<Message, ProtocolError>> for WebSocket {
    fn handle(&mut self, item: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
        match item.unwrap() {
            Message::Text(txt) => match serde_json::from_str::<WebSocketMessage>(&txt.to_string()).unwrap() {
                WebSocketMessage::SendChatMessage { chat, message } => {}
                WebSocketMessage::ReadChat(chat) => {}
                WebSocketMessage::Typing(chat) => {}
                _ => panic!()
            }
            Message::Ping(msg) => ctx.pong(msg.as_ref()),
            Message::Close(_) => todo!(),
            _ => panic!(),
        }
    }
}

#[get("/ws")]
async fn ws_index(data: Data<State>, user: AuthedUser, r: HttpRequest, stream: Payload) -> WebResult<HttpResponse> {
    ws::start(WebSocket { data, user: user.id }, &r, stream)
}

pub fn config(cfg: &mut web::ServiceConfig) {
    cfg.service(ws_index);
}
e5nqia27

e5nqia271#

您正在寻找actix::spawn

ctx.run_interval(POLL_INTERVAL, |myself, ctx| {
    // I want to do async stuff in here
    actix::spawn(async { my_async_fn().await; });
});

相关问题