1. 程式人生 > >spring整合websocket js的編寫

spring整合websocket js的編寫

  之前說了websocket的服務端編寫,下面說說客戶端的編寫,若要看服務端可以檢視連結:https://blog.csdn.net/jared_he2017/article/details/79886131


1.  首先通過服務端提供的websocket連線地址進行初始化websocket

var websocket;   //全域性的
function initSocket(){
if(!websocket){
if('WebSocket' in window) {
websocket = new WebSocket("ws://" + ctx + "/websocket");

} else if('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://" + ctx + "/websocket");
} else {
websocket = new SockJS("http://" + ctx + "/sockjs/websocket");
}
}

}


2. 然後為websocket連線定義各種事件方法

$(function() {
   initSocket();
    
    websocket.onopen = function(evnt) {
        console.log("  websocket.onopen  ");
    };

    websocket.onmessage = function(evnt) {
//   

var base64 = base64Encode(evnt.data);
//    $("#msg").append("<p><img src='data:image/png;base64," + evnt.data + "' /></p>");
    var msgObj = eval("(" + evnt.data + ")");
    setMsg(msgObj);
        console.log("  websocket.onmessage   ");
    };

    websocket.onerror = function(evnt) {
        console.log("  websocket.onerror  ");
    };


    websocket.onclose = function(evnt) {
        console.log("  websocket.onclose  ");
initSocket();
    };

});


3. 如果你的服務段是通過nginx進行反代理,那麼要定時傳送心跳包來保持連線,具體時間只有比nginx與tomcat的最大保持連線時長小就行,我的配置為60s,當然ie和edge瀏覽器會自動傳送心跳包

function  sendHeartData(){
var userAgent = navigator.userAgent; //取得瀏覽器的userAgent字串 
var isOpera = userAgent.indexOf("Opera") > -1; //判斷是否Opera瀏覽器 
var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判斷是否IE瀏覽器 
var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判斷是否IE的Edge瀏覽器 
var isFF = userAgent.indexOf("Firefox") > -1; //判斷是否Firefox瀏覽器 
var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判斷是否Safari瀏覽器 
var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判斷Ch

if(isIE || isEdge)  //ie、edge瀏覽器會自動傳送心跳包,無需手動傳送
return;


if(websocket && websocket.readyState && websocket.readyState == 1) {
websocket.send("java.nio.HeapByteBuffer");
}
}


var  heartData = setInterval(sendHeartData, 60000);   // 每分鐘傳送一次心跳包