websocket 封装及使用

1.websocket.js   封装好了,直接在项目中引入使用即可

class jtWebSocket{
  //构造函数
  constructor() {
    this.webSocket = null; //webSocket对象
    this.url = null; //webSocket连接的url
    this.lastHeartBeat = 0; // 上一次心跳时间
    this.connectTimer = null; // 重连定时器
    this.isPauseConnet = null; // 是否要暂停连接
  }
  initWebSocket (url) { // 初始化weosocket
    this.url = url
    this.webSocket = new WebSocket(this.url)
    this.lastHeartBeat = new Date().getTime()
    if (this.webSocket) {
      this.webSocket.onopen = this.websocketonopen
      this.webSocket.onerror = this.websocketonerror
      this.webSocket.onclose = this.websocketclose
    }
  }
  websocketonopen () { // 连接建立之后执行send方法发送数据
    clearInterval(this.connectTimer)
    this.isPauseConnet = true
    this.connectTimer = null
    this.connectTimer = setInterval(this.checkConnect, 5000)
  }
   // 连接建立失败重连
  websocketonerror (callback) {
    this.isLoadImg = false
    if(t

你可能感兴趣的:(websocket,vue,websocket,vue)