websocket封装代码

tow.js文件

/**
传入的参数说明
 * @param {*} ws_protocol wss or ws 
 * @param {*} ip 
 * @param {*} port 
 * @param {*} paramStr 加在ws url后面的请求参数,形如:name=张三&id=12
 * @param {*} param 作为tio.ws对象的参数,由业务自己使用,框架不使用
 * @param {*} handler 
 * @param {*} heartbeatTimeout 心跳时间 单位:毫秒
 * @param {*} reconnInterval 重连间隔时间 单位:毫秒
 * @param {*} binaryType 'blob' or 'arraybuffer';//arraybuffer是字节
 */
 function tio (ws_protocol, ip, port, paramStr, param,handler,heartbeatTimeout, reconnInterval, binaryType) {
  this.ip = ip
  this.port = port
  this.url = ws_protocol + '://' + ip + ':' + port
  this.binaryType = binaryType || 'arraybuffer'
  this.events = {};//事件处理
  this.type=null
  if (paramStr) {
    this.url += '?' + paramStr
    this.reconnUrl = this.url + "&"
  } else {
    this.reconnUrl = this.url + "?"
  }
  this.reconnUrl += "tiows_reconnect=true";
  this.param = param

  // this.handler = handler
  this.heartbeatTimeout = heartbeatTimeout
  this.reconnInterval = reconnInterval

  this.lastInteractionTime = function () {
    if (arguments.length == 1) {
      this.lastInteractionTimeValue = arguments[0]
    }
    return this.lastInteractionTimeValue
  }

  this.heartbeatSendInterval = heartbeatTimeout / 2

  this.connect = function (isReconnect) {
    var _url = this.url;
    if (isReconnect) {
      _url = this.reconnUrl;
    }
    var ws = new WebSocket(_url)
    this.ws = ws

    ws.binaryType = this.binaryType; // 'arraybuffer'; // 'blob' or 'arraybuffer';//arraybuffer是字节
    var self = this
    ws.onopen = function (event) {
      // self.handler.onopen.call(self.handler, event, ws)
      self.fire('wsonopen')
      self.lastInteractionTime(new Date().getTime())

      self.pingIntervalId = setInterval(function () {
        self.ping(self)
      }, self.heartbeatSendInterval)
    }
    ws.onmessage = function (event) {
      // self.handler.onmessage.call(self.handler, event, ws)
      self.fire('wsonmessage',event)
      self.lastInteractionTime(new Date().getTime())
    }
    ws.onclose = function (event) {
      clearInterval(self.pingIntervalId) // clear send heartbeat task

      try {
        // self.handler.onclose.call(self.handler, event, ws)
      } catch (error) {}
      console.log('1')
      if(!self.type){
        console.log('2')
        self.reconn(event)
      }
    }
    ws.onerror = function (event) {
      // self.handler.onerror.call(self.handler, event, ws)
    }

    return ws
  }

  this.reconn = function (event) {
    var self = this
    setTimeout(function () {
      var ws = self.connect(true)
      self.ws = ws
    }, self.reconnInterval)
  }
  this.closeSocket = function () {
    console.log('3')
   this.type=true
   clearInterval(this.reconnInterval)
   this.ws.close()
  }
  this.ping = function () {
    var iv = new Date().getTime() - this.lastInteractionTime(); // 已经多久没发消息了
    // 单位:秒
    if ((this.heartbeatSendInterval + iv) >= this.heartbeatTimeout) {
      // this.handler.ping(this.ws)
    }
  };

  this.send = function(data){
    this.ws.send(data);
  };
  // 订阅事件,每个事件仅允许订阅一次,后订阅的会覆盖之前的
  this.on = (eventName, handler) => {
    if (this.events[eventName]) {
        this.events[eventName].funcs = [handler];
    } else {
        this.events[eventName] = {
            funcs: [handler]
        }
    }
  }
  // 发布消息
  this.fire = (eventName, arg1, arg2) => {
      if (!this.events) return;
      if (!this.events[eventName]) return console.log('未订阅' + eventName + '事件');
      let funcs = this.events[eventName].funcs || [];
      funcs.forEach(func => {
          if (func && typeof func === 'function') {
              func(arg1, arg2);
          }
      });
  }
  // 移除注册事件
  this.removeEvent = (eventName) => {
      if (eventName === 'all') {
          this.events = null;
          return false;
      }
      if (!this.events[eventName]) return;
      this.events[eventName].funcs = [];
  }
}
export default tio;


websocket.ts文件

import tio from '/@/utils/tiows';
import $baseApi from '/@/config';
const ws_protocol = 'ws'; // ws 或 wss
const ip = $baseApi.agentSocketUrl;
const port = 9101;
const heartbeatTimeout = 5000; // 心跳超时时间,单位:毫秒
const reconnInterval = 1000 * 3; // 重连间隔时间,单位:毫秒
const binaryType = 'blob'; // 'blob' or 'arraybuffer';//arraybuffer是字节
const param = '';
let queryString = 'isClient=0';
let agentSocket:any = null;
agentSocket = new tio(
    ws_protocol,
    ip,
    port,
    queryString,
    param,
    null,
    heartbeatTimeout,
    reconnInterval,
    binaryType
),
agentSocket.connect()

export default agentSocket

在这里插入图片描述

相关文章

学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习...
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面...
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生...
Can’t connect to local MySQL server through socket \'/v...
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 ...
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服...