在 JSR-356 中广播服务器发起的 WebSocket 消息的最佳实践是什么?
澄清一下,我知道使用注释时回复甚至广播是如何工作的@OnMessage
,但我想从服务器发送一个事件,而不先从客户端接收消息。换句话说,我想我需要在MessageServerEndpoint
下面的代码中引用实例。
我见过以下解决方案,但它使用静态方法并且不是很优雅。
@ServerEndpoint(value = "/echo")
public class MessageServerEndpoint {
private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
@OnOpen
public void onOpen(Session session) {
sessions.add(session);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
sessions.remove(session);
}
// Static method - I don't like this at all
public static void broadcast(String message) {
for (Session session : sessions) {
if (session.isOpen()) {
session.getBasicRemote().sendText(message);
}
}
}
}
public class OtherClass {
void sendEvent() {
MessageServerEndpoint.broadcast("test");
// How do I get a reference to the MessageServerEndpoint instance here instead?
}
}