Parcourir la source

webSocket断线重连功能开发

hurugang il y a 3 ans
Parent
commit
dbced1b719

+ 153 - 75
src/main/resources/static/js/common/evaluation-websocket.js

@@ -1,90 +1,168 @@
-var websocket = null;
+var webSocket = null;
 var ipAddress = "";
+var webSocketType=null;
+var lockReconnect = false;//避免重复连接
+var serverAddress=null;
+/**
+ * webSocket处理方法
+ */
+function initEventHandle() {
+    webSocket.onerror = function () {
+        reConnect();
+        console.log("连接出错");
+    }
+    webSocket.onopen = function () {
+        //心跳检测重置
+        heartCheck.reset().start();
+        console.log("连接成功");
+    }
+    webSocket.onmessage = function (event) {
+        //如果获取到消息,心跳检测重置 拿到任何消息都说明当前连接是正常的
+        heartCheck.reset().start();
+        if (event.data == "HeartBeat") {
+            //忽略心跳的信息,因为只要有消息进来,断线重连就会重置不会触发
+        } else {
+            var data = JSON.parse(event.data);
+            if (data.type == "url") {
+                window.open(data.url, '_self');
+                return;
+            }
+            //推送价格
+            if (data.type == "priceData") {
+
+            }
+            if (data.type == "content") {
+                if (data.id == "client_evaluate") {
+                    $("#client_evaluate").show();
+                    $("#client_index").hide();
+                    $("#client_price").hide();
+                    var mp3 = $("#mp3");
+                    mp3.attr("src", data.messageAudio);
+                    mp3.get(0).play();
+                    return;
+                } else if (data.id == "client_price") {
+                    $("#client_price").show();
+                    $("#client_evaluate").hide();
+                    $("#client_index").hide();
+                    $("#pName").text(data.name);
+                    $("#pGender").text(data.call);
+                    $("#needPay").text(data.needPay);
+                    $("#pay").text(data.pay);
+                    $("#changeAmount").text(data.changeAmount);
+                    //播放语音
+                    var mp3 = $("#mp3");
+                    mp3.attr("src", data.messageAudio);
+                    mp3.get(0).play();
+                    return;
+                }
+            }
+        }
+        console.log("收到消息" + event.data);
+    }
+    webSocket.onclose = function () {
+        reConnect();
+        console.log("退出连接");
+    }
+    window.onbeforeunload = function () {
+        reConnect();
+        webSocket.close(3000, "强制关闭");
+    }
+}
+
+/**
+ * 建立连接
+ * @param type
+ */
+function createWebSocket() {
+    try {
+        if ('WebSocket' in window) {
+            $.ajax({
+                type: "GET",
+                url: '/thmz/getWebSocketHost',
+                contentType: "application/json;charset=UTF-8",
+                dataType: "json",
+                headers: {'Accept': 'application/json'},
+                success: function (res) {
+                    if (res.code == 0) {
+                        serverAddress = res.data;
+                        serverAddress = serverAddress + "evaluationWebSocket/" + ipAddress + "/" + webSocketType;
+                        webSocket = new WebSocket(serverAddress);
+                        initEventHandle();
+                    }
+                }
+            });
+        } else {
+            alert('当前浏览器不支持WebSocket,请更换浏览器');
+        }
+    }catch (e) {
+        reConnect();
+    }
+}
+
 /**
  * 创建webSocket
  * @param type
  */
 function openEvaluationWebSocket(type) {
+    webSocketType=type;
     if (!ipAddress) {
         getUserIP(function(ip) {
             ipAddress = ip
-            if('WebSocket' in window){
+            createWebSocket();
+        })
+    }
+}
 
-                $.ajax({
-                    type: "GET",
-                    url: '/thmz/getWebSocketHost',
-                    contentType: "application/json;charset=UTF-8",
-                    dataType: "json",
-                    headers: {'Accept': 'application/json'},
-                    success: function (res) {
-                        if (res.code == 0) {
-                            var serverAddress=res.data;
-                            serverAddress=serverAddress+"evaluationWebSocket/"+ipAddress+"/"+type;
-                            websocket = new WebSocket(serverAddress);
-                            websocket.onerror = function(){
-                                console.log("连接出错");
-                            }
-                            websocket.onopen = function(){
-                                console.log("连接成功");
-                            }
-                            websocket.onmessage  = function(event){
-                                var data = JSON.parse(event.data);
-                                if(data.type=="url"){
-                                    window.open(data.url, '_self');
-                                    return;
-                                }
-                                //推送价格
-                                if(data.type=="priceData"){
 
-                                }
-                                if(data.type=="content"){
-                                    if(data.id=="client_evaluate"){
-                                        $("#client_evaluate").show();
-                                        $("#client_index").hide();
-                                        $("#client_price").hide();
-                                        var mp3 = $("#mp3");
-                                        mp3.attr("src",data.messageAudio);
-                                        mp3.get(0).play();
-                                        return;
-                                    }else if(data.id=="client_price"){
-                                        $("#client_price").show();
-                                        $("#client_evaluate").hide();
-                                        $("#client_index").hide();
-                                        $("#pName").text(data.name);
-                                        $("#pGender").text(data.call);
-                                        $("#needPay").text(data.needPay);
-                                        $("#pay").text(data.pay);
-                                        $("#changeAmount").text(data.changeAmount);
-                                        //播放语音
-                                        var mp3 = $("#mp3");
-                                        mp3.attr("src",data.messageAudio);
-                                        mp3.get(0).play();
-                                        return;
-                                    }
-                                }
-                                console.log("收到消息" + event.data);
-                            }
-                            websocket.onclose = function(){
-                                console.log("退出连接");
-                            }
-                            window.onbeforeunload = function(){
-                                clos();
-                            }
 
-                            function clos(){
-                                websocket.close(3000,"强制关闭");
-                            }
-                            function send(){
-                                var msg = document.getElementById('text').value;
-                                websocket.send(msg);
-                            }
-                        }
-                    }
-                });
-            }else{
-                alert('当前浏览器不支持WebSocket,请更换浏览器');
-            }
-        })
+/**
+ * 重新连接
+ */
+function reConnect() {
+    if (lockReconnect) {
+        return;
     }
+    lockReconnect = true;
+    //没连接上会一直重连,设置延迟避免请求过多
+    setTimeout(function () {
+        if ('WebSocket' in window) {
+            webSocket = new WebSocket(serverAddress);
+            initEventHandle();
+        } else {
+            alert('当前浏览器不支持WebSocket,请更换浏览器');
+        }
+        console.log("正在重连,当前时间" + new Date())
+        lockReconnect = false;
+    }, 5000); //这里设置重连间隔(ms)
 }
 
+
+
+//心跳检测
+var heartCheck = {
+    timeout: 15000,//毫秒
+    timeoutObj: null,
+    serverTimeoutObj: null,
+    reset: function () {
+        clearTimeout(this.timeoutObj);
+        clearTimeout(this.serverTimeoutObj);
+        return this;
+    },
+    start: function () {
+        var self = this;
+        this.timeoutObj = setTimeout(function () {
+            //这里发送一个心跳,后端收到后,返回一个心跳消息,
+            //onmessage拿到返回的心跳就说明连接正常
+            try {
+                webSocket.send("HeartBeat");
+                console.log("HeartBeat");
+            } catch (e) {
+                webSocket.close();
+                reConnect();
+            }
+            self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置,说明后端主动断开了
+                webSocket.close();//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
+            }, self.timeout)
+        }, this.timeout)
+    }
+}

+ 108 - 34
src/main/resources/static/js/common/notice-websocket.js

@@ -1,7 +1,8 @@
 //@ sourceURL=notice-websocket.js
-var websocket = null;
+var webSocket = null;
 var userIdCode = "";
-
+var lockReconnect = false;//避免重复连接
+var serverAddress=null;
 /**
  * 构造未读消息列表
  * @param data 消息列表集合
@@ -54,12 +55,46 @@ function fitNoticeList(data) {
     }
 }
 
+
 /**
- * 创建webSocket
+ * webSocket处理方法
  */
-function openNoticeWebSocket() {
-    if (!userIdCode) {
-        userIdCode = localStorage.getItem("userIdCode");
+function initEventHandle() {
+    webSocket.onerror = function () {
+        reConnect();
+        console.log("连接出错");
+    }
+    webSocket.onopen = function () {
+        //心跳检测重置
+        heartCheck.reset().start();
+        console.log("连接成功");
+    }
+    webSocket.onmessage = function (event) {
+        //如果获取到消息,心跳检测重置 拿到任何消息都说明当前连接是正常的
+        heartCheck.reset().start();
+        if (event.data == "HeartBeat") {
+            //忽略心跳的信息,因为只要有消息进来,断线重连就会重置不会触发
+        } else {
+            var data = JSON.parse(event.data);
+            fitNoticeList(data);
+            console.log("收到消息" + event.data);
+        }
+    }
+    webSocket.onclose = function () {
+        reConnect();
+        console.log("退出连接");
+    }
+    window.onbeforeunload = function () {
+        reConnect();
+        webSocket.close(3000, "强制关闭");
+    }
+}
+
+/**
+ * 建立连接
+ */
+function createWebSocket() {
+    try {
         if ('WebSocket' in window) {
             $.ajax({
                 type: "GET",
@@ -69,41 +104,80 @@ function openNoticeWebSocket() {
                 headers: {'Accept': 'application/json'},
                 success: function (res) {
                     if (res.code == 0) {
-                        var serverAddress = res.data;
+                        serverAddress = res.data;
                         serverAddress = serverAddress + "noticeWebSocket/" + userIdCode;
-                        websocket = new WebSocket(serverAddress);
-                        websocket.onerror = function () {
-                            console.log("连接出错");
-                        }
-                        websocket.onopen = function () {
-                            console.log("连接成功");
-                        }
-                        websocket.onmessage = function (event) {
-                            var data = JSON.parse(event.data);
-                            fitNoticeList(data);
-                            console.log("收到消息" + event.data);
-                        }
-                        websocket.onclose = function () {
-                            console.log("退出连接");
-                        }
-                        window.onbeforeunload = function () {
-                            clos();
-                        }
-
-                        function clos() {
-                            websocket.close(3000, "强制关闭");
-                        }
-
-                        function send() {
-                            var msg = document.getElementById('text').value;
-                            websocket.send(msg);
-                        }
+                        webSocket = new WebSocket(serverAddress);
+                        initEventHandle();
                     }
                 }
             });
         } else {
             alert('当前浏览器不支持WebSocket,请更换浏览器');
         }
+    } catch (e) {
+        reConnect();
+    }
+}
+
+/**
+ * 创建webSocket
+ */
+function openNoticeWebSocket() {
+    if (!userIdCode) {
+        userIdCode = localStorage.getItem("userIdCode");
+        createWebSocket();
     }
 }
 
+
+/**
+ * 重新连接
+ */
+function reConnect() {
+    if (lockReconnect) {
+        return;
+    }
+    lockReconnect = true;
+    //没连接上会一直重连,设置延迟避免请求过多
+    setTimeout(function () {
+        if ('WebSocket' in window) {
+            webSocket = new WebSocket(serverAddress);
+            initEventHandle();
+        } else {
+            alert('当前浏览器不支持WebSocket,请更换浏览器');
+        }
+        console.log("正在重连,当前时间" + new Date())
+        lockReconnect = false;
+    }, 5000); //这里设置重连间隔(ms)
+}
+
+
+//心跳检测
+var heartCheck = {
+    timeout: 15000,//毫秒
+    timeoutObj: null,
+    serverTimeoutObj: null,
+    reset: function () {
+        clearTimeout(this.timeoutObj);
+        clearTimeout(this.serverTimeoutObj);
+        return this;
+    },
+    start: function () {
+        var self = this;
+        this.timeoutObj = setTimeout(function () {
+            //这里发送一个心跳,后端收到后,返回一个心跳消息,
+            //onmessage拿到返回的心跳就说明连接正常
+            try {
+                webSocket.send("HeartBeat");
+                console.log("HeartBeat");
+            } catch (e) {
+                webSocket.close();
+                //reConnect();
+            }
+            self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置,说明后端主动断开了
+                webSocket.close();//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
+                //reConnect();
+            }, self.timeout)
+        }, this.timeout)
+    }
+}