如何封装webSocket

实际工作中可能会遇到需要封装WebSocket的场景,以下基于vue做了WebSocket的封装,包括心跳机制和重连

// 创建构造函数
const QueryWebSocket = function (obj) {
  obj = obj || {}
  obj.url = `wss://${process.env.NODE_ENV === "development" ? "xxx.xxx.com" : location.host}${obj.url}`
  const defaultObj = {
    url: '',
    lockReconnect: false,
    ws: '',
    tt: '',
    timeout: 30000,
    timeoutObj: null,
    queryData(){}
  }
  this.config = Object.assign(defaultObj, obj)
  if ('WebSocket' in window) {
    // console.log('支持WebSocket')
    const that = this
    setTimeout(function () {
      that.createWebSocket()
    }, 1000)
  } else {
    alert('该浏览器不支持WebSocket')
  }
}
QueryWebSocket.prototype = {
  QueryWebSocket: QueryWebSocket,
  reset: function () {
    const that = this
    clearInterval(that.config.timeoutObj)
    // console.log('进入此处关闭连接的吗')
    this.config.ws.onclose()
  },
  start: function () {
    const that = this
    that.config.timeoutObj = setInterval(function () {
      const message = 'I'
      that.config.ws.send(message) // 启动心跳
    }, 15000)
  },
  // 创建webSocket
  createWebSocket: function () {
    try {
      // 成功
      // console.log('createWebSocket');
      this.config.ws = new WebSocket(this.config.url)
      this.webSocketInit() // 初始化webSocket连接函数
      // this.config.createSuccess()
    } catch (e) {
      // 失败
      // console.log(e,'catch')
      // 重连函数
      this.webSocketReconnect(this.config.url)
    }
  },
  // 像websocket发送信息
  sendContent: function (data) {
    this.config.ws.send(JSON.stringify(data))
  },
  // 初始化方法,成功后执行
  webSocketInit: function () {
    const that = this
    // 连接关闭函数
    that.config.ws.onclose = function (type) {
      // // console.log('type会传进来么', type)
      // // console.log('连接已关闭...', new Date())
      clearInterval(that.config.timeoutObj)
      if (type !== 'close') {
        setTimeout(() => {
          that.webSocketReconnect(that.config.url) // 如果连接关闭则重连
        }, 3000)
      } else {
        that.config.ws.close()
        that.config.ws = null
        that.lockReconnect = true
      }
    }
    // 连接错误函数
    that.config.ws.onerror = function () {
      // console.log('连接错误...', new Date())
      clearInterval(that.config.timeoutObj)
      setTimeout(() => {
        that.webSocketReconnect(that.config.url) // 如果连接错误则重连
      }, 3000)
    }
    // 连接建立,发送信息
    that.config.ws.onopen = function () {
      // // console.log('链接成功')
      that.config.ws.send('I')
      that.start() // 订阅业务发送之后启动心跳检测机制
    }
    // 业务订阅成功后接受服务端推送消息  ,其实是个字符串
    that.config.ws.onmessage = function (evt) {
      if (evt.data !== 'O') {
        if (JSON.parse(evt.data).content !== 'PONG') {
          that.config.queryData(JSON.parse(evt.data))
        }
      }
    }
  },
  // 重连
  webSocketReconnect: function (url) {
    // console.log('reconnect');
    const that = this
    if (that.lockReconnect) {
      return
    }
    // // console.log('socket 连接断开,正在尝试重新建立连接')
    that.lockReconnect = true
    that.tt && clearTimeout(that.tt)
    that.tt = setTimeout(function () {
      that.lockReconnect = false
      that.createWebSocket(url)
    }, 4000)
  }
}
export default QueryWebSocket

使用示例

项目中导入QueryWebSocket

import QueryWebSocket from './websocket'

methods中写入方法

    createWebSocket() {
      let url = `这里写wss地址`
      this.webSocket = new QueryWebSocket({
        url: url,
        queryData: () => {
        },
      })
    },
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值