【问题标题】:Rust Actix Actor send message to actorRust Actix Actor 向 Actor 发送消息
【发布时间】:2021-09-11 10:06:57
【问题描述】:

如何向其他参与者发送消息?


pub struct MyWs {
}

impl Actor for MyWs {
    type Context = ws::WebsocketContext<Self>;
}

impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
    fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
        match msg {
            Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
            Ok(ws::Message::Text(message)) => {

                //considering that here he sent the message to self
                ctx.text(message);

                //how to do something like this
                //find the actor by index (or uuid) and send text
                //actors[0].text(message);
                //
            },
            Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
            Ok(ws::Message::Close(reason)) => ctx.close(reason),
            _ => (),
        }
    }
}


#[get("/ws")]
pub async fn websocket(req: HttpRequest, stream: web::Payload,) -> actix_web::Result<HttpResponse> {
    let resp = ws::start(
        MyWs {},
        &req,
        stream,
    );
    return resp;
}

我可以制作一个演员的 hashMap 吗?

pub struct MyWs { sessions: HashMap<Uuid, Socket> }

以后

self.sessions.text(message)

我是 rust 新手,我没有看到保存套接字(上下文或参与者)以找到它并发送消息的方法。

【问题讨论】:

    标签: websocket rust actor


    【解决方案1】:

    您可能需要查看使用 actix web 的聊天室应用的官方示例https://github.com/actix/examples/blob/743af0ff1a9be6fb1cc13e6583108463c89ded4d/websockets/chat/src/main.rs

    有三个关键点:

    1. 创建另一个服务器actor并获取它的地址。

      let server = server::ChatServer::new(app_state.clone()).start();

    2. 将服务器actor的地址设置为HttpServer的应用数据。

      HttpServer::new(move || {
          App::new()
              .data(app_state.clone())
              // copy server actor's address into app
              .data(server.clone())
              .service(web::resource("/").route(web::get().to(|| {
                  HttpResponse::Found()
                      .header("LOCATION", "/static/websocket.html")
                      .finish()
              })))
              .route("/count/", web::get().to(get_count))
              // websocket
              .service(web::resource("/ws/").to(chat_route))
              // static resources
              .service(fs::Files::new("/static/", "static/"))
      })
      .bind("127.0.0.1:8080")?
      .run()
      .await
      
    3. 在函数chat_route中启动websocket actor时存储地址。然后你可以随时使用该地址发送消息

    /// Entry point for our websocket route
    async fn chat_route(
        req: HttpRequest,
        stream: web::Payload,
        srv: web::Data<Addr<server::ChatServer>>,
    ) -> Result<HttpResponse, Error> {
        ws::start(
            WsChatSession {
                id: 0,
                hb: Instant::now(),
                room: "Main".to_owned(),
                name: None,
                addr: srv.get_ref().clone(),
            },
            &req,
            stream,
        )
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 2013-04-30
      • 2019-10-17
      • 2015-05-29
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      相关资源
      最近更新 更多