webscoket封装

封装

export function NewWebSocket () {
  this.websocket = null
  this.heartbeat_timer = null
  this.active_close = null
  this.init = (params) => {
    this.websocket = new WebSocket(params.url)
    this.websocket.onopen = (data) => {
      this.heartbeat()
      if (params.onopen) {
        params.onopen('webSocket已连接', data)
      }
    }
    this.websocket.onmessage = (data) => {
      if (params.onmessage) {
        let obj=JSON.parse(data.data)
        // console.log('onmessage', obj)
        if (obj&&obj.type&&obj.type=='ping'){
          return
        }
        params.onmessage(data)
      }
    }
    this.websocket.onclose = () => {
      clearInterval(this.heartbeat_timer)
      if (this.active_close) {
        if (params.onclose) {
          params.onclose('连接已手动关闭')
        }
      } else {
        this.reconnect(params)
        if (params.onclose) {
          params.onclose('连接已关闭, 正在重连')
        }
      }
    }
    this.websocket.onerror = () => {
      clearInterval(this.heartbeat_timer)
      if (params.onerror) {
        params.message('连接发生错误!等待五秒后重连')
        setTimeout(() => {
          this.reconnect(params)
        },5000)
      }
    }
  }
  this.heartbeat = () => {
    console.log('执行心跳')
    if (this.heartbeat_timer) {
      clearInterval(this.heartbeat_timer)
    }
    this.heartbeat_timer = setInterval(() =>{
      this.websocket.send(
        JSON.stringify({
          type: 'ping'
        })
      )
    },10000)
  }
  this.reconnect = (params) => {
    console.log('执行重连')
    this.active_close = false
    if (this.websocket) {
      this.websocket.close()
    }
    this.init(params)
  }
  this.close = () => {
    console.log('手动关闭,无需重连')
    clearInterval(this.heartbeat_timer)
    this.active_close = true
    this.websocket.close()
  }
}

调用

import {NewWebSocket} from '@/utils/messageWebscoket'
	this.socket = new NewWebSocket()
    this.socket.init({
        url: `xxxxxx`, // 自己的ws 地址
        onopen: (msg, data) => {
          console.log(msg, data)
        },
        onmessage: (res) => {
          console.log('scoket消息', res)
        },
        onclose: (data) => {
          console.log(data)
        }
      })
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值