Skip to content

Executing send_message from Actix Websocket Chat example #608

Closed

Description

@NielDuysters

Hello.

In the Websocket chat example server.rs has this code snippet:

/// Handler for Message message.
impl Handler<ClientMessage> for ChatServer {
    type Result = ();

    fn handle(&mut self, msg: ClientMessage, _: &mut Context<Self>) {
        self.send_message(&msg.room, msg.msg.as_str(), msg.id);
    }
}

I want to execute send_message() from any place in my code. For example from a Actix route-function. This way I can make a kind of push-notification system based on this example.

This is my attempt:

async fn send_test(srv: web::Data<actix::Addr<websocket_server::ChatServer>>) {
    srv.get_ref().send_message("main", "test message", 1);
}

Error:

error[E0599]: no method named `send_message` found for reference `&actix::Addr<ChatServer>` in the current scope
    --> src/main.rs:1161:19
     |
1161 |     srv.get_ref().send_message("main", "test message", 1);
     |                   ^^^^^^^^^^^^ method not found in `&actix::Addr<ChatServer>`

For more information about this error, try `rustc --explain E0599`.

So how would I execute send_message() from any place in my code? Thanks!

Activity

  1. NielDuysters commented on Feb 27, 2023

    @NielDuysters
    Author

    Solution:

    async fn send_test(
        srv: web::Data<actix::Addr<websocket_server::ChatServer>>,
    ) -> Result<HttpResponse> {
        srv.send(websocket_server::ClientMessage {
            id: 0,
            msg: "Test 123".to_string(),
            room: "main".to_string(),
        })
        .await;
    
        Ok(HttpResponse::Ok().content_type("text/plain").body("OK"))
    }
    
  2. locked and limited conversation to collaborators on Feb 27, 2023
  3. converted this issue into a discussion #609 on Feb 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions