原生方式实现websocket功能

 在vue布局组件中使用

data() {
    return {
      path: 'ws://82.157.123.54:9010/ajaxchattest',
      // path: 'ws://192.168.0.139:9999/api/notification/topic/server',
      websocket: undefined
    }
  },
mounted() {
    // 初始化
    this.init()
  },
  destroyed() {
    // 销毁监听
    this.websocket.close()
  },
  methods: {
    init() {
      try {
        if (typeof WebSocket === 'undefined') {
          this.$notify({
            title: '警告',
            message: '您的浏览器不支持websocket!',
            type: 'warning'
          })
        } else {
          // 实例化websocket
          this.websocket = new WebSocket(this.path)
          // 监听websocket连接
          this.websocket.onopen = this.onopen
          // 监听websocket错误信息
          this.websocket.onerror = this.onerror
          // 监听websocket消息
          this.websocket.onmessage = this.onMessage
          // 监听websocket关闭
          this.websocket.onclose = this.onclose
          this.websocketSend()
        }
      } catch (error) {
        console.log(error)
      }
    },
    onopen() {
      console.log('websocket连接成功')
    },
    onerror() {
      console.log('连接错误')
      this.reconnect()
    },
    onMessage(e) {
      console.log(e.data)
    },
    onclose() {
      console.log('websocket已经关闭')
      this.reconnect()
    },
    websocketSend(text) {
      try {
        setInterval(() => {
          this.websocket.send(new Date())
        }, 3000)
      } catch (err) {
        console.log('send failed (' + err.code + ')')
      }
    },
    reconnect() {
      var that = this
      if (that.lockReconnect) return
      that.lockReconnect = true
      // 没连接上会一直重连,设置延迟避免请求过多
      setTimeout(() => {
        console.info('尝试重连...')
        that.init()
        that.lockReconnect = false
      }, 5000)
    }
  }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值