Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to broadcast a message using raw Spring 4 WebSockets without STOMP?

In this great answer https://stackoverflow.com/a/27161986/4358405 there is an example of how to use raw Spring4 WebSockets without STOMP subprotocol (and without SockJS potentially).

Now my question is: how do I broadcast to all clients? I expected to see an API that I could use in similar fashion with that of pure JSR 356 websockets API: session.getBasicRemote().sendText(messJson);

Do I need to keep all WebSocketSession objects on my own and then call sendMessage() on each of them?

like image 635
TMG Avatar asked Nov 25 '15 07:11

TMG


People also ask

How do I send a message to a specific user WebSocket Spring boot?

These steps need to be performed: Generate a Spring Security Principal name by UUID for each newly connected client by using DefaultHandshakeHandler. Store the UUID if a new message is received. Use @SendToUser instead of @SendTo annotation in the WebSocket controller.

Is STOMP deprecated?

This project is no longer maintained. If you encounter bugs with it or need enhancements, you can fork it and modify it as the project is under the Apache License 2.0.

How do you use WebSockets in Spring?

In order to tell Spring to forward client requests to the endpoint , we need to register the handler. Start the application- Go to http://localhost:8080 Click on start new chat it opens the WebSocket connection. Type text in the textbox and click send. On clicking end chat, the WebSocket connection will be closed.

What is WebSocket STOMP?

The WebSocket API enables web applications to handle bidirectional communications whereas STOMP is a simple text-orientated messaging protocol. A Bidirectional WebSocket allows a web server to initiate a new message to a client, rather than wait for the client to request updates.


1 Answers

I found a solution. In the WebSocket handler, we manage a list of WebSocketSession and add new session on afterConnectionEstablished function.

private List<WebSocketSession> sessions = new ArrayList<>();

synchronized void addSession(WebSocketSession sess) {
    this.sessions.add(sess);
}

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    addSession(session);
    System.out.println("New Session: " + session.getId());
}

When we need to broadcast, just enumerate through all session in list sessions and send messages.

for (WebSocketSession sess : sessions) {
        TextMessage msg = new TextMessage("Hello from " + session.getId() + "!");
        sess.sendMessage(msg);
}

Hope this help!

like image 157
novax Avatar answered Oct 14 '22 04:10

novax