Vue中使用WebSocket

     initWebSocket() {
      //初始化websocket
      let wsuri = 'ws地址'
      this.ws = new WebSocket(wsuri)
      this.ws.onmessage = this.websocketonmessage
      this.ws.onopen = this.websocketonopen
      this.ws.onerror = this.websocketonerror
      this.ws.onclose = this.websocketclose
    },
    websocketonopen() {
      console.log('连接 websocket 成功')
    },
    websocketonmessage(e) {
      //获取websocket推送的数据
      let msg = e.data
      console.log(msg)
    },
    // 连接失败时重新连接
    websocketonerror() {
      this.initWebSocket()
    },
    // 断开链接后报错
    websocketclose(e) {
      console.log('断开连接', e)
      //this.initWebSocket() //断开后重新连接
    },

 

posted @ 2020-11-19 09:10  yw3692582  阅读(2030)  评论(0编辑  收藏  举报