zoukankan      html  css  js  c++  java
  • websocket 心跳重连

    websocket 的基本使用:

    var ws = new WebSocket(url);
    ws.onclose = function () { //something
    reconnect(); // 自定义的 websocket 重连方法 }; ws.onerror = function () { //something
    reconnect(); // 自定义的 websocket 重连方法 }; ws.onopen = function () { //something }; ws.onmessage = function (event) { //something }

    想要 websocket 一直保持连接,我们在 onclose 和 onerror 方法中执行重连方法。
    但是当信号不好,网络临时断开时,websocket 连接断开而不会执行 onclose 方法,这时我们就无法重连 websocket 了。
    所以需要针对断网情况使用心跳重连的方式。

    var heartCheck = {
        timeout: 60000,//60s
        timer: null,
        reset: function(){  // 终止 start 的 setTimerout,不让 ws.send() 执行,然后重新执行 start
            clearTimeout(this.timer);
         this.start(); }, start: function(){ this.timer= setTimeout(function(){ ws.send("HeartBeat"); // send 方法执行,如果是断网状态,则会自动触发 onclose 方法,实现重连。重连方法中会执行 start 方法,再次开始心跳检测,所以这里使用的 setTimeout 而不是 setInterval }, this.timeout) } } ws.onopen = function () { heartCheck.start(); // onopen 的时候执行 start 开始心跳检测 };
    ws.onmessage = function (event) {  // 接收到后端的消息执行 reset
        heartCheck.reset();
    }
  • 相关阅读:
    C++模板学习之优先队列实现
    static 和const分别怎么用,类里面static和const可以同时修饰成员函数吗?
    C和C++的区别
    C++多态例子_虚函数
    转:master公式(主方法)
    C++11最常用的新特性如下
    转:哈夫曼树详解
    linux shell脚本
    linux 正则表达式
    linux shell命令
  • 原文地址:https://www.cnblogs.com/3body/p/8622329.html
Copyright © 2011-2022 走看看