I\'ve browsed a lot of Web Socket examples, presentation slides and they are mostly concentrated on a rather simple scenarios in which client-server communication is initiat
Store the active sessionList
in another class SessionManager
.
List<Session> socketSessions = new ArrayList<>();
Add incoming session in @OnOpen
to list. Remove session from list in @OnClose
@OnClose
public void close(Session session) {
sessionManager.removeSession(session);
}
To send a message to everyone,
public void broadcast(String message){
for(Session session: sessionList){
session.getBasicRemote().sendText(message);
}
}
You can use the sessionManager.broadcast()
method wherever the event triggers.
Here is a complete example of how websocket can be used to make push with HTML5 websocket API. https://metamug.com/article/java-push-notification-with-websocket.php
I do it this way (no client request is needed):
@ServerEndpoint("/hello")
public class HelloWebSocket {
@OnOpen
public void greetTheClient(Session session){
try {
session.getBasicRemote().sendText("Hello stranger");
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
}
I have implemented a solution similar to your problem using omnifaces socket component. Notifications are triggered by JMS messages and recipients may be specific users or all of them. The blog post url https://konstpan.wordpress.com/2018/03/25/push-notifications-in-a-jee-web-application-secured-by-keycloak/
Probably this is not most elegant way but just to demonstrate idea. Method broadcast() will send message to all connected clients.
@ServerEndpoint("/echo")
public class ServerEndPoint {
private static Set<Session> userSessions = Collections.newSetFromMap(new ConcurrentHashMap<Session, Boolean>());
@OnOpen
public void onOpen(Session userSession) {
userSessions.add(userSession);
}
@OnClose
public void onClose(Session userSession) {
userSessions.remove(userSession);
}
@OnMessage
public void onMessage(String message, Session userSession) {
broadcast(message);
}
public static void broadcast(String msg) {
for (Session session : userSessions) {
session.getAsyncRemote().sendText(msg);
}
}
}