webSocket+HeadBeat

最近需要用到webSocket,来实时接收长链接发送过来的信息,同时又要发送心跳给服务端。直接贴代码吧。

 1 var ws;//websocket实例
 2 var heartCheck;
 3 var lockReconnect = false;//避免重复连接
 4 var wsUrl = "ws://116.62.207.100:8080/websocket";
 5 function createWebSocket(url) {
 6     try {
 7         ws = new WebSocket(url);
 8         initEventHandle();
 9     } catch (e) {
10         reconnect(url);
11     }     
12 }
13 function initEventHandle() {
14     ws.onclose = function () {
15       console.log("webscoket关闭状态即将重连...")
16       reconnect(wsUrl);
17     };
18     ws.onerror = function () {
19       console.log("webscoket异常状态即将重连...")
20         reconnect(wsUrl);
21     };
22     ws.onopen = function () {
23       console.log("webscoket已经链接 心跳检测重置中...")
24         //心跳检测重置
25         heartCheck.reset().start();
26     };
27     ws.onmessage = function (event) {
28       console.log("【收到】:" + event.data);
29       //如果获取到消息,心跳检测重置
30       //拿到任何消息都说明当前连接是正常的
31       heartCheck.reset().start();
32     }
33 }
34 function reconnect(url) {
35     if(lockReconnect) return;
36     lockReconnect = true;
37     //没连接上会一直重连,设置延迟避免请求过多
38     setTimeout(function () {
39         createWebSocket(url);
40         lockReconnect = false;
41     }, 2000);
42 }
43 //心跳检测
44 heartCheck = {
45     timeout: 90000,//90秒
46     timeoutObj: null,
47     serverTimeoutObj: null,
48     reset: function(){
49         clearTimeout(this.timeoutObj);
50         clearTimeout(this.serverTimeoutObj);
51         return this;
52     },
53     start: function(){
54         var self = this;
55         //这里发送一个心跳,后端收到后,返回一个心跳消息,
56         //onmessage拿到返回的心跳就说明连接正常
57         send("HeadBeat");
58         this.timeoutObj = setTimeout(function(){
59             console.log("【走到这一步的原因很简单,因为你没有收到心跳消息,那么N秒后将自动关闭重连】")
60             self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了
61                 ws.close();//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
62             }, self.timeout)
63         }, this.timeout)
64     }
65 }
66 createWebSocket(wsUrl);
67 //WebSocket发送请求
68 function send(message) {
69   if (!window.WebSocket) { return; }
70   if (ws.readyState == WebSocket.OPEN) {
71     console.log('【发送】:'+JSON.stringify(message))
72     ws.send(JSON.stringify(message));
73   } else {
74     layui.use('layer', function(){
75       var layer = layui.layer;
76       layer.msg('您还未连接上服务器,请刷新页面重试!',{icon: 0});
77     })  
78   }
79 }
原文地址:https://www.cnblogs.com/studyshufei/p/8643060.html