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() //斷開后重新連接
    },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM