WebSocket

export default class MessageSocket {
  constructor(url) {
    this.url = url
    this.ws = null
    this.count = 0
    this.status = false
  }

  init() {
    if (typeof WebSocket) {
      const _this = this
      if (this.status) return
      this.ws = new WebSocket(this.url)

      this.ws.onopen = function () {
        _this.status = true
        _this.count = 0
        console.log('webSocket连接成功!')

        setInterval(() => {
          _this.ws.send(1)
        }, 5000);
      }

      this.ws.onerror = this.onerror.bind(this)

      this.ws.onclose = function (e) {
        console.log('webSocket连接断开!')
        this.status = false
        if (this.count < 100) {
          setTimeout(() => {
            _this.init()
            _this.count++
            console.log(`webSocket连接失败,正在尝试第${_this.count}次重连...`)
          }, 5000)
        }
      }
      return this.ws
    } else {
      this.$message.error('该浏览器不支持WebSocket通信')
    }
  }

  // onmessage(e) {
  //   console.log('webSocket onmessage', e)
  //   const wsAlarmInfo = JSON.parse(e.data)

  //   localStorage.setItem('ws-alarm', JSON.stringify({
  //     wsAlarmInfo,
  //     timeStamp: new Date().getTime()
  //   }))
  // }

  onerror(error) {
    console.log('webSocket onerror', error)
    this.status = false
    if (this.count < 100) {
      setTimeout(() => {
        this.init()
        this.count++
        console.log(`webSocket连接失败,正在尝试第${this.count}次重连...`)
      }, 5000)
    }
  }
}
import MessageSocket from '@/api/socket.js'

 initWebSocket() {
      console.log(window.location)
      const url = window.location.protocol === 'https:' ? `wss://${window.location.hostname}/ctm01itlgtelwn/socketServer/admin` : `ws://${window.location.host}/ctm01itlgtelwn/socketServer/admin`

      // const url = 'ws://10.194.213.181:17016/ctm01itlgtelwn/socketServer/admin'
      const webSocket = new MessageSocket(url).init()
      webSocket.onmessage = this.onmessage
    },

    onmessage(e) {
      const wsAlarmInfo = JSON.parse(e.data)
      console.log(wsAlarmInfo, 'webSocket onmessage')
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值