How to implement push to client using Java EE 7 WebSockets?

前端 未结 4 1483
生来不讨喜
生来不讨喜 2020-12-31 12:17

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

相关标签:
4条回答
  • 2020-12-31 12:59

    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

    0 讨论(0)
  • 2020-12-31 13:06

    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());
        }
       }
    }
    
    0 讨论(0)
  • 2020-12-31 13:10

    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/

    0 讨论(0)
  • 2020-12-31 13:11

    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);
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题