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

前端 未结 4 1501
生来不讨喜
生来不讨喜 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 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

提交回复
热议问题