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();
    }
  • 相关阅读:
    3.学习Dispatcher
    2学习Application
    学习WPF-1
    Content-Type说明
    AspNet Core定时任务
    Asp.Net Core跨域配置
    学习Emmet
    Asp.Net Core存储Cookie不成功
    服务端编码和解码
    C#7特性
  • 原文地址:https://www.cnblogs.com/3body/p/8622329.html
Copyright © 2011-2022 走看看