【vue】自定義一個websocket工具函式

前端小高發表於2021-12-02

備註一個近期在做的專案下使用的websocket工具函式

(實際應用場景為,某院下的排隊叫號系統,需要使用到websocket連線,且自定義回撥函式並按需處理 )

使用步驟大致如下:

  1. 專案根路徑下新建一個websocket.js檔案,檔案內容如下

    let ws = null
    let _data = null
    let _url = null
    let _callback = null
    let hearBeatTimer = null
    let reconnectTimer = null
    let reconnectNum = 0 // 重連次數
    const time = 3000 // 心跳間隔
    const reconnectTime = 5000 // 重連超時
    export function webSocket(url = '', data = '', callback = () => {}) {
      // 初始化
      _url = url // 地址
      _data = data // 傳送訊息
      _callback = callback // 回撥函式,利用閉包
      createWebSocket() // 建立 webSocket
    }
    export function getWebSocket() {
      return ws
    }
    
    export function closeWebSocket() {
      console.log('關閉WebSocket')
      if (ws) {
     ws.onerror = () => {}
     ws.onclose = () => {}
     ws.close()
      }
      ws = null
      _data = null
      _url = null
      _callback = () => {}
      // timeoutTimer = null
      hearBeatTimer = null
      reconnectTimer = null
    }
    
    function createWebSocket() {
      console.log('建立WebSocket')
      if (!_url) return
      if (ws) {
     ws.close()
     ws = null
      }
      ws = new WebSocket(_url)
      ws.onopen = function() {
     sendMessage()
     heartBeat()
      }
      ws.onmessage = function(e) {
     console.log('訊息事件:', e)
     // clearTimeout(timeoutTimer)
     if (typeof _callback === 'function') {
       _callback(e)
     }
     reconnectNum = 0
     heartBeat()
      }
      ws.onerror = function() {
     reconnect()
      }
      ws.onclose = function() {
     reconnect()
      }
    }
    
    function heartBeat() {
      if (hearBeatTimer) {
     clearTimeout(hearBeatTimer)
      }
      hearBeatTimer = setTimeout(() => {
     if (ws && ws.readyState === 1) {
       // 如果連線正常
       sendMessage()
       // setTimeoutTimer()
     } else {
       reconnect()
     }
      }, time)
    }
    
    function sendMessage() {
      console.log('傳送訊息:', _data)
      if (!ws) return
      switch (Object.prototype.toString.call(_data)) {
     case '[object Object]':
       ws.send(JSON.stringify(_data))
       break
     case '[object String]':
       ws.send(_data)
      }
    }
    
    
    function reconnect() {
      if (reconnectTimer) {
     clearTimeout(reconnectTimer)
      }
      reconnectTimer = setTimeout(() => {
     reconnectNum++
     console.log('重連WebSocket')
     console.log('重連次數:', reconnectNum)
     webSocket(_url, _data, _callback)
      }, reconnectTime)
    }
    window.onbeforeunload = () => {
      closeWebSocket()
    }
    

2.在app.vue 下引用並初始化websocket

import { webSocket } from './websocket.js'

export default {
created() {
  this.init()
},
methods: {
    init() {
      this.onWebSocket()
    },
    // 開啟 socket
    onWebSocket() {
     // 模擬地址
      const url =  'wss://www.baidu.com?uuid=‘
// 心跳包傳送內容
        const data = {
          to: -1,
          text: 'ping', // 內容
        }
        console.log('data', data)
        webSocket(url, data, this.handleWSCallBack)
      },
 // 處理socket 回撥
    handleWSCallBack(data) {
       // console.log('data', e.data)
      //do something
}
}
}

剩餘函式部分,各位小夥伴可以按需調整該回撥引數

備註:以上CODE部分內容,要感謝下面這位阿遠同學的幫忙,下面的他的某金賬號,各位如有興趣可以關注下(裡面乾貨略多)

某金賬號

相關文章