How to broadcast a message using raw Spring 4 WebS

2019-02-09 14:40发布

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?

2条回答
干净又极端
2楼-- · 2019-02-09 14:40

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!

查看更多
何必那么认真
3楼-- · 2019-02-09 14:53

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

查看更多
登录 后发表回答