问题描述
在一个很好的答案中 https://stackoverflow.com/a/27161986/4358405 有一个示例使用不带STOMP子协议(也可能不带SockJS)的原始Spring4 WebSockets.
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).
现在我的问题是:如何向所有客户广播?我期望看到一个可以与纯JSR 356 websockets API类似使用的API:session.getBasicRemote().sendText(messJson);
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);
我需要自己保留所有WebSocketSession
对象,然后在每个对象上调用sendMessage()
吗?
Do I need to keep all WebSocketSession
objects on my own and then call sendMessage()
on each of them?
推荐答案
我找到了解决方案.在WebSocket处理程序中,我们管理WebSocketSession的列表,并在afterConnectionFounded函数上添加新的会话.
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);
}
希望获得帮助!
这篇关于如何在不使用STOMP的情况下使用原始Spring 4 WebSockets广播消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!