TMG
TMG

Reputation: 2740

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?

Upvotes: 10

Views: 6087

Answers (2)

novax
novax

Reputation: 481

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 " + sess.getId() + "!");
    sess.sendMessage(msg);
  }

Hope this help!

Upvotes: 6

s.ijpma
s.ijpma

Reputation: 940

As far as i know and can gather from the documentation here you can't broadcast using the WebSocketHandler.

Instead you should use Stomp over WebSocket configured by a WebSocketMessageBrokerConfigurer as described here.

Use a SimpMessagingTemplate anywhere in your code to send messages to subscribed clients as described here

Upvotes: 0

Related Questions