vue 中如何使用websocket

vue 中如何使用websocket
前端和后端的交互模式最常见的就是前端发数据请求,从后端拿到数据后展示到页面中。如果前端不做操作,后端不能主动向前端推送数据,这也是http协议的缺陷。

因此,一种新的通信协议应运而生—websocket,他最大的特点就是服务端可以主动向客户端推送消息,客户端也可以主动向服务端发送消息,实现了真正的平等

项目中代码如下(在此记录一下,做个备注)

(亲测有效,也是踩过很多坑的,对代码进一步做了完善)

created() {
    this.initWebSocket() // 连接websocket
 }
 destoryed() {
     this.websock.close() // 离开路由之后断开websock
 }
  methods: {
    /*
    * 初始化websocket
    */
    initWebSocket() {
      if (!this.websock) {
        const wsurl = '后端提供的地址'
        this.websock = new WebSocket(wsurl)
        this.websock.onmessage = this.websocketonmessage
        this.websock.onopen = this.websocketonopen
        this.websock.onerror = this.websocketonerror
        this.websock.onclose = this.websocketclose
      } else {
        console.log('websocket已连接')
      }
    },
    /**
     * 连接建立之后执行send方法发送数据
     */
    websocketonopen(dialogQuery) {
      this.sendPing() // 发送心跳
    },
    /**
     * 连接失败重新连接
     */
    websocketonerror() {
      clearInterval(this.setIntervalWesocketPush)
      this.websock.close()
      this.initWebSocket() // 重连
    },
    /**
     * 数据接收
     */
    websocketonmessage(e) {
      console.log(JSON.parse(e.data), '------ start --------')
    },
    /**
     * 数据发送
     */
    websocketsend(data) {
      if (this.websock !== null && this.websock.readyState === 3) {
        this.websock.close()
        var time = setInterval(function() {
          this.initWebSocket() // 重连
          clearInterval(time)
        }, Math.ceil(Math.random() * 5) === 0 ? 1000 : Math.ceil(Math.random() * 5) * 3000) // 随机3秒内重连
      } else if (this.websock.readyState === 1) {
        this.websock.send(JSON.stringify(data))
      } else if (this.websock.readyState === 0) {
        setTimeout(() => {
          this.websock.send(JSON.stringify(data))
        }, 2000)
      }
    },
    /**
     * 关闭
     */
    websocketclose(e) {
      clearInterval(this.setIntervalWesocketPush)
    },
    /**
     * 发送心跳
     */
    sendPing() {
      this.websock.send('ping')
      this.setIntervalWesocketPush = setInterval(() => {
        this.websock.send('ping')
      }, 60000)
    },
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值