WebSocket

发布于:2024-08-08 ⋅ 阅读:(205) ⋅ 点赞:(0)
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')
    },

网站公告

今日签到

点亮在社区的每一天
去签到