java websocket 消息推送

1. maven 引入依賴javascript

<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. 編寫map轉換器,其實若是須要傳遞給頁面一個map,須要把map轉換成json【fastJson】格式html

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. 編寫獲取httpSession的配置,在webSocket獲取session中用戶登錄信息java

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. 編寫webSocket,須要注意的是在這裏沒法注入service,個人作法是把查出來的數據封裝好,調用webSocket推送數據 web

@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消息】 user:{}",user);
                sessionMap.put(this.username, session);
            }
    
            log.info("【websocket消息】 有新的鏈接,總數:{}",webSocketSet.size());
        }
    
        @OnClose
        public void onClose() {
            webSocketSet.remove(this);
            sessionMap.remove(this.username);
            log.info("【websocket消息】鏈接斷開,總數:"+webSocketSet.size());
        }
        
        @OnMessage
        public void onMessage(String message) throws IOException,InterruptedException {
            log.info("【websocket消息】 收到客戶端發來的消息:{}",message);
        }
        
        public void sendMessage(String message){
            for (WebSocket webSocket : webSocketSet) {
                log.info("【websocket消息】 廣播消息:{}",message);
                try {
                    webSocket.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 
         * <p>Description: TODO</p>
         * <p>Company: 梧州學院</p> 
         * @author 胡宇鵬
         * @date 2018年1月23日 上午10:29:45
         * @param json
         * @param plagMusicFlag 播放聲音標記:0.不播放 1.播放
         */
        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消息】 廣播消息:map");
                try {
                    webSocket.session.getBasicRemote().sendObject(json);
                } catch (EncodeException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        /**
         * 
         * <p>Description: 單獨發送信息給指定的用戶</p>
         * <p>Company: 梧州學院</p> 
         * @author 胡宇鵬
         * @date 2018年1月23日 上午10:29:04
         * @param userList
         * @param json 須要接收信息的用戶集合
         * @param plagMusicFlag 播放聲音標記:0.不播放 1.播放
         */
        public void sendMessage(List<SysUser> userList,Map<String, Object> json,Integer plagMusicFlag) {
            if(userList.size() == 0 && json.size() > 0){
                // 說明是拒絕的狀況
                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. 在service注入了webSocket以後直接調用webSocket.sendMessage(...)方法主動推送數據,根據我的的項目須要編寫sendMessage(...)這個方法。其實也就是執行了增、刪等操做的時候主動刷新待處理消息提示,在這裏就不演示了json


 6. 編寫webSocket.js,好比我在左側的菜單欄引入了這個js
 api

(function(){
      var websocket = null;
      //var url = '127.0.0.1:8080/cl'; // 本地測試
    
      function getProjectPath(){
        //獲取當前網址,如: http://localhost:8083/uimcardprj/share/meun.jsp
        var curWwwPath = window.document.location.href;
        //獲取主機地址以後的目錄,如: uimcardprj/share/meun.jsp
        var pathName = window.document.location.pathname;
        var pos = curWwwPath.indexOf(pathName);
        //獲取主機地址,如: http://localhost:8083
        var localhostPaht = curWwwPath.substring(7, pos); // 去除http://
        //獲取帶"/"的項目名,如:/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('該瀏覽器不支持websocket!');
      }
    
      websocket.onopen = function (event) {
        console.log('創建鏈接');
      };
    
      websocket.onclose = function (event) {
        console.log('鏈接關閉');
      };
    
      websocket.onmessage = function (event) {
        //console.log('收到消息:' + 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();   // 播放聲音
        }
    
      };
    
      websocket.onerror = function () {
        layer.msg('websocket通訊發生錯誤!');
      };
    
      window.onbeforeunload = function () {
        websocket.close();
      };
    
      function buildHtmlWaitCount(num,id){
        if(num > 0){
          $(id).html(num);
          return;
        }
        $(id).html("");
      }
    
    })();
相關文章
相關標籤/搜索