Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Actix-ws does not broadcast the messages. #481

Open
Necoo33 opened this issue Nov 15, 2024 · 0 comments
Open

Actix-ws does not broadcast the messages. #481

Necoo33 opened this issue Nov 15, 2024 · 0 comments

Comments

@Necoo33
Copy link

Necoo33 commented Nov 15, 2024

In the actix-ws crate, only that example given in documentations and any other guidance exist:

pub async fn websocket_chat_controller(req: HttpRequest, body: Payload) -> actix_web::Result<impl Responder> {
    let (response, mut session, mut msg_stream) = actix_ws::handle(&req, body)?;

    spawn(async move {
        while let Some(Ok(msg)) = msg_stream.recv().await {
            match msg {
                Message::Ping(bytes) => {
                    println!("ping mesajı!");
                    if session.pong(&bytes).await.is_err() {
                        return;
                    }
                },
                Message::Text(bytes) => {
                    println!("our bytes: {}", bytes);
                    session.text(bytes).await.unwrap();
                },
                _ => break
            }
        };

        let _ = session.close(None).await;
    });

    Ok(response)
}

That code not "Solely" broadcastes the messages, it only grabs "Session"s and "Message"s that came from certain client. For broadcasting them, you have to store them globally by your own, for example, i did it with adding that code on global scope:

    let sessions: Arc<Mutex<Vec<Session>>> = Arc::new(Mutex::new(vec![]));

and passed it to the server as web::Data:

.app_data(web::Data::new(sessions.clone()))

then basically grab it on the websocket route, push the session variable in that vector, then iterate that vector in Message::Text and call session.text() on each iteration. If you want, i can add a most basic example on actix/examples. Because it looks hard to understand in first appearance, especially for beginners to the framework.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant