2
头图

Remarks a websocket tool function used in a recent project

(The actual application scenario is that the queuing system in a hospital needs to use websocket connection, and customize the callback function and process it on demand)

The usage steps are roughly as follows:

  1. Create a new websocket.js file under the project root path, the content of the file is as follows

    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. Reference and initialize websocket under app.vue

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
}
}
}

For the rest of the function, you can adjust the callback parameters as needed

Remarks: For the above CODE part, I would like to thank the student Ayuan below for his help, and one of his gold accounts below. If you are interested, you can pay attention to it (there are slightly more dry goods)

gold account


前端小高
552 声望10 粉丝

Hey!