java websocket message push

Posted by studio805 on Tue, 05 May 2020 15:34:33 +0200

1. maven introduces dependency

    <dependency>
	  <groupId>com.alibaba</groupId>
	  <artifactId>fastjson</artifactId>
	  <version>1.2.3</version>
    </dependency> 
    <dependency>
        <groupId>javax.websocket</groupId>
        <artifactId>javax.websocket-api</artifactId>
        <version>1.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
    </dependency>


2. Write a map converter. In fact, if you need to pass a map to the page, you need to convert the map to json [fastJson] format

    public class EncoderUtil implements Encoder.Text<Map<String, Object>>{
    
        @Override
        public void destroy() {}
    
        @Override
        public void init(EndpointConfig arg0) {}
    
        @Override
        public String encode(Map<String, Object> map) throws EncodeException {
            return JSON.toJSONString(map);
        }    
    }


3. Write the configuration to obtain the httpSession, and obtain the user login information in the session in webSocket

    public class GetHttpSessionConfigurator extends Configurator{
    
        @Override
        public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
            HttpSession httpSession = (HttpSession)request.getHttpSession();
            sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
        }        
    }


4. When writing webSocket, it should be noted that service cannot be injected here. My approach is to encapsulate the found data and call webSocket to push data

    @Component
    @ServerEndpoint(value ="/ws/webSocket", 
                    encoders = { EncoderUtil.class },
                    configurator = GetHttpSessionConfigurator.class)
    public class WebSocket {
        
        private Session session;
        private HttpSession httpSession;
        
        private SysUser user;
        private String username;
    
        private static final Logger log = LoggerFactory.getLogger(WebSocket.class);    
        private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
        private static Map<String,Session> sessionMap =  new ConcurrentHashMap<String,Session>();
        
        @OnOpen
        public void onOpen(Session session,EndpointConfig config) {
            this.session = session;
            webSocketSet.add(this);
            httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
            
            if(httpSession != null){
                this.user = (SysUser) httpSession.getAttribute("login_user");
                this.username = this.user.getUsername();
                //log.info("[websocket message] user:{}",user);
                sessionMap.put(this.username, session);
            }
    
            log.info("[websocket Message] has a new connection,Total:{}",webSocketSet.size());
        }
    
        @OnClose
        public void onClose() {
            webSocketSet.remove(this);
            sessionMap.remove(this.username);
            log.info("[websocket Message] disconnected,Total:"+webSocketSet.size());
        }
        
        @OnMessage
        public void onMessage(String message) throws IOException,InterruptedException {
            log.info("[websocket Message] received the message from the client:{}",message);
        }
        
        public void sendMessage(String message){
            for (WebSocket webSocket : webSocketSet) {
                log.info("[websocket Message] broadcast message:{}",message);
                try {
                    webSocket.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 
         * <p>Description: TODO</p>
         * <p>Company: Wuzhou University</p> 
         * @author Hu Yupeng
         * @date 2018 10:29:45 am, January 23, 2010
         * @param json
         * @param plagMusicFlag Play sound tag: 0. Do not play 1. Play
         */
        public void sendMessage(Map<String, Object> json,Integer plagMusicFlag) {
            if(plagMusicFlag == null){
                json.put("plagMusicFlag",0);
            }
            json.put("plagMusicFlag", plagMusicFlag);
            for (WebSocket webSocket : webSocketSet) {
                log.info("[websocket Message] broadcast message:map");
                try {
                    webSocket.session.getBasicRemote().sendObject(json);
                } catch (EncodeException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        /**
         * 
         * <p>Description: Send information to specified users separately</p>
         * <p>Company: Wuzhou University</p> 
         * @author Hu Yupeng
         * @date 2018 January 23, 2010 10:29:04 am
         * @param userList
         * @param json Collection of users who need to receive information
         * @param plagMusicFlag Play sound tag: 0. Do not play 1. Play
         */
        public void sendMessage(List<SysUser> userList,Map<String, Object> json,Integer plagMusicFlag) {
            if(userList.size() == 0 && json.size() > 0){
                // Description of rejection
                sendMessage(json,0);
                return ;
            }
            json.put("plagMusicFlag", plagMusicFlag);
            if(plagMusicFlag == null){
                json.put("plagMusicFlag",1);
            }
            Iterator<Entry<String,Session>> entries = sessionMap.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String,Session> entry = entries.next();
                for (SysUser user : userList) {
                    if(user.getUsername().equals(entry.getKey())){
                        try {
                            entry.getValue().getBasicRemote().sendObject(json);
                            continue;
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (EncodeException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }        
        }
        
        public void sendMessage(SysUser user,Map<String, Object> json,Integer plagMusicFlag){
            List<SysUser> userList = new ArrayList<SysUser>();
            userList.add(user);
            sendMessage(userList,json,plagMusicFlag);
        }    
    }

 

5. After the service is injected into webSocket, directly call the webSocket.sendMessage(...) method to actively push data, and write the sendMessage(...) method according to the needs of individual projects. In fact, when the operation of adding or deleting is performed, the message prompt to be processed will be refreshed actively, which will not be demonstrated here


6. Write webSocket.js. For example, I introduced this JS in the menu bar on the left
 

    (function(){
      var websocket = null;
      //Var url ='127.0.0.1:8080 / CL '; / / local test
    
      function getProjectPath(){
        //Get the current website, such as: http://localhost:8083/uimcardprj/share/meun.jsp
        var curWwwPath = window.document.location.href;
        //Get the directory after the host address, such as uimcardprj/share/meun.jsp
        var pathName = window.document.location.pathname;
        var pos = curWwwPath.indexOf(pathName);
        //Get the host address, such as: http://localhost:8083
        var localhostPaht = curWwwPath.substring(7, pos); // Remove http://
        //Get the project name with "/", such as / uimcardprj
        var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
        return (localhostPaht + projectName);
      }
    
      if('WebSocket' in window) {
        websocket = new WebSocket('ws://' + getProjectPath() + '/ws/webSocket');
      }else {
        layer.msg('This browser does not support websocket!');
      }
    
      websocket.onopen = function (event) {
        console.log('Establish a connection');
      };
    
      websocket.onclose = function (event) {
        console.log('Connection closed');
      };
    
      websocket.onmessage = function (event) {
        //console.log('received message: '+ event.data);
        var result = eval('(' + event.data + ')');
    
        buildHtmlWaitCount(result.fAppr,"#waitFApprCount");
        buildHtmlWaitCount(result.sAppr,"#waitSApprCount");
        buildHtmlWaitCount(result.tAppr,"#waitTApprCount");
        buildHtmlWaitCount(result.sch,"#waitSchCount");
        buildHtmlWaitCount(result.rc,"#waitRCCount");
    
        if(result.plagMusicFlag == 1){
          document.getElementById('schTip').play();   // Play sound
        }
    
      };
    
      websocket.onerror = function () {
        layer.msg('websocket Communication error!');
      };
    
      window.onbeforeunload = function () {
        websocket.close();
      };
    
      function buildHtmlWaitCount(num,id){
        if(num > 0){
          $(id).html(num);
          return;
        }
        $(id).html("");
      }
    
    })();

Topics: JSON Session JSP Maven