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

前端 未结 4 1516
生来不讨喜
生来不讨喜 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 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 userSessions = Collections.newSetFromMap(new ConcurrentHashMap());
    
        @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);
            }
        }
    
    }
    

提交回复
热议问题