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

旧街凉风 提交于 2019-11-30 14:00:48

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!

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

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