websocket帮助类

最近项目有用到websocket来实现部分功能.遂封装了一个单间的工具类.
使用方法:

    var wsUrl = 'ws://xxxx'; // url
    var ws = new webSocketTool({
      url: wsUrl,
      pingTimeout: 5000,
      pongTimeout: 10000,
      reconnectTimeout: 2000,
      pingMsg: "ping",
      repeatLimit: 2
    });
    //实例化成功回调
    ws.onopen = function () {
      console.log('连接成功!');
      ws.send('hello');
    };
    //发送消息回调
    ws.onmessage = function (e) {
      console.log('接收到服务器返回数据:' + e.data);
    };
    //出错回调
    ws.onerror = function () {
      console.log('连接错误');
    };
    // 重连回调
    ws.onreconnect = function (time) {
      console.log('重连次数:' + time);
    };
    //关闭回调
    ws.onclose = function () {
      console.log('已关闭');
    };

完整工具类:

/**
 * websocket工具类
 */
"use strict";
(function (window) {
  var WebSocketTool = function (options) {
    this.url = options.url; // websocket服务端接口地址
    this.pingTimeout = options.pingTimeout || 15000;//每隔15秒发送一次心跳,如果收到任何后端消息定时器将会重置
    this.pongTimeout = options.pongTimeout || 10000;//ping消息发送之后,10秒内没收到后端消息便会认为连接断开
    this.reconnectTimeout = options.reconnectTimeout || 2000;//尝试重连的间隔时间
    this.pingMsg = options.pingMsg || 'ping';//ping消息值
    this.repeatLimit = options.repeatLimit || null;//重连尝试次数。默认不限


    // 内部使用 禁止修改
    this.ws = null; // websocket 实例
    this.repeat = 0; // 已经重连次数

    //外部重写钩子函数
    this.onclose = function () {
    };
    this.onerror = function () {
    };
    this.onopen = function () {
    };
    this.onmessage = function () {
    };
    this.onreconnect = function () {
    };

    this.initial(); // 初始函数
  };
  WebSocketTool.prototype = {
    // 初始函数
    initial: function () {
      if (!this.url) {
        alert('url不存在');
        return;
      }
      try {
        this.ws = new WebSocket(this.url);
        this.EventHandle()
      } catch (e) {
        this.reconnect();
        throw e;
      }
    },
    // 事件绑定
    EventHandle: function () {
      this.ws.onclose = () => {
        this.onclose();
        this.reconnect();// 重连
      };
      this.ws.onerror = () => {
        this.onerror();
        this.reconnect(); // 重连
      };
      this.ws.onopen = () => {
        this.repeat = 0;
        this.onopen();
        //心跳检测重置
        this.heartCheck();
      };
      this.ws.onmessage = (event) => {
        this.onmessage(event);
        //如果获取到消息,心跳检测重置
        //拿到任何消息都说明当前连接是正常的
        this.heartCheck();
      };
    },
    reconnect: function () {
      if (this.repeatLimit > 0 && this.repeatLimit <= this.repeat) return;//限制重复
      if (this.lockReconnect || this.forbidReconnect) return;
      this.lockReconnect = true;
      this.repeat++;//必须在lockReconnect之后,避免进行无效计数
      this.onreconnect(this.repeat);
      //没连接上会一直重连,设置延迟避免请求过多
      setTimeout(() => {
        this.initial();
        this.lockReconnect = false;
      }, this.reconnectTimeout);
    },
    send: function (msg) {
      this.ws.send(msg);
    },
    //心跳检测
    heartCheck: function () {
      this.heartReset();
      this.heartStart();
    },
    heartStart: function () {
      if (this.forbidReconnect) return;//不再重连就不再执行心跳
      this.pingTimeoutId = setTimeout(() => {
        //这里发送一个心跳,后端收到后,返回一个心跳消息,
        //onmessage拿到返回的心跳就说明连接正常
        this.ws.send(this.pingMsg);
        //如果超过一定时间还没重置,说明后端主动断开了
        this.pongTimeoutId = setTimeout(() => {
          //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
          this.ws.close();
        }, this.pongTimeout);
      }, this.pingTimeout);
    },
    heartReset: function () {
      clearTimeout(this.pingTimeoutId);
      clearTimeout(this.pongTimeoutId);
    },
    close: function () {
      //如果手动关闭连接,不再重连
      this.forbidReconnect = true;
      this.heartReset();
      this.ws.close();
    }
  };
  if (window) window.webSocketTool = WebSocketTool;
}(window));

参考:https://github.com/zimv/websocket-heartbeat-js

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 8,134评论 1 3
  • 1.图片浏览控件MWPhotoBrowser 实现了一个照片浏览器类似 iOS 自带的相册应用,可显示来自手机的图...
    万忍阅读 5,360评论 0 6
  • 27年前的1992年结束了我的学业,师范是我进过的最高学府,于是我的人生有个小小的遗憾,没进过大学校园,没领略过大...
    曼殊斐儿_bcbb阅读 3,101评论 0 9
  • 偶遇上了朋友,他请我吃了顿酸菜肉沫盖饭
    一点金汐阅读 952评论 0 1
  • 前言 最近项目中突然要将用到图片(项目使用Fresco)及视频(项目使用TextureView绘制纹理,Surfa...
    PeytonWu阅读 10,272评论 0 1