websocket心跳机制封装

 <!DOCTYPE html> 
 <html> 
 <head> 
     <meta charset="utf-8"> 
     <title>websocket通讯</title> 
 </head> 
 <script src="[https://cdn.bootcss.com/jquery/3.3.1/jquery.js](https://cdn.bootcss.com/jquery/3.3.1/jquery.js)"></script> 
 <script> 
 function createWebSocket() { 
     var wsUrl = document.getElementById("wsUrl").value; 
     try { 
         ws = new WebSocket(wsUrl); 
         init(wsUrl); 
     } catch(e) { 
         console.log('catch'); 
         reconnect(wsUrl); 
     } 
 }
 function send(){
     var msg = document.getElementById("msg").value; 
     ws.send(msg); 
 } 
 function init(wsUrl) { 
     ws.onclose = function () { 
     // createWebSocket(); 
       console.log('链接关闭'); 
    }; 
     ws.onerror = function() { 
     createWebSocket(); 
      console.log('发生异常了'); 
    }; 
     ws.onopen = function () { 
     console.log("websocket已打开:" + wsUrl); 
    //心跳检测重置 
     heartCheck.start();
    }; 
 ws.onmessage = function (msg) { 
    if(msg.data == "001"){ 
     console.log("心跳包"); 
 } 
     console.log(msg.data); 
//拿到任何消息都说明当前连接是正常的 
     heartCheck.start(); 
   } 
 } 

//心跳检测 
 var heartCheck = { 
     timeout: 30000, //每隔30秒发送心跳 
     severTimeout: 5000, //服务端超时时间 
     timeoutObj: null, 
     serverTimeoutObj: null, 
     start: function(){ 
     var _this = this; 
     this.timeoutObj && clearTimeout(this.timeoutObj); 
     this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj); 
     this.timeoutObj = setTimeout(function(){ 
 //这里发送一个心跳,后端收到后,返回一个心跳消息, 
 //onmessage拿到返回的心跳就说明连接正常 
 ws.send('{"type":3}'); // 心跳包 
     //计算答复的超时时间 
     _this.serverTimeoutObj = setTimeout(function() { 
     ws.close(); 
     }, _this.severTimeout); 
 }, this.timeout) 
     } 
 } 

</script> 
 <body> 
 <input type="text" id="wsUrl" value="ws://enbool.club/dscreen/ws/barrage/1"/> 
 <input type="text" id="msg" value="{}"/> 
 <p>【操作】:<div><button onclick="createWebSocket()">开启socket</button></div> 
 <p>【操作】:<div><button onclick="send()">发送</button></div> 
 </body> 
</html> 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容