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

ε祈祈猫儿з 提交于 2019-12-30 04:41:08

问题


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?


回答1:


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!




回答2:


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



来源:https://stackoverflow.com/questions/33910639/how-to-broadcast-a-message-using-raw-spring-4-websockets-without-stomp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!