How can I share actix WebSocketContext between threads?

I have the following code

type Ctx = ws::WebsocketContext<Ws>;
pub struct WsStore {
    connections: Vec<Mutex<Ctx>>,
}
lazy_static::lazy_static! {
    static ref WSS:Arc<Mutex<WsStore>> = {
        Arc::new(Mutex::new(WsStore{
            connections:vec![]
        }))
    };
}
struct Ws {
    pub user: User,
}

impl Actor for Ws {
    type Context = ws::WebsocketContext<Self>;
    fn started(&mut self, ctx: &mut Self::Context) {
        ctx.text(format!("connected {}", self.user.id))
    }
}

impl StreamHandler<Result<Message, ws::ProtocolError>> for Ws {
    fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
        match msg {
            Ok(Message::Text(t)) => message_handler(&t, ctx),
            Ok(Message::Binary(_)) => ctx.close(None),
            Ok(Message::Ping(m)) => ctx.pong(&m),
            Ok(Message::Close(r)) => ctx.close(r),
            k => {
                let _ = dbg!(k);
            }
        }
    }
}

and I can respond to messages fine but I cant understand how I can push contexts into some global store so I can write message to them or broadcast messages without receiving a message from user ?

It turns out Actix provides a method called address for actors implemented via actix::AsyncContext and that can be shared between threads

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.