1. 程式人生 > 其它 >uniapp小程式webSocket封裝使用

uniapp小程式webSocket封裝使用

目錄

1,前言

最近在做IOT的專案,裡面有個小程式要用到webSocket,借這個機會,封裝了一個uniapp小程式適用的Socket類,具體實現如下。

2,程式碼實現

class webSocketClass {
  constructor(url, interval) {
    this.url = url
    this.data = null
    this.isCreate = false // WebSocket 是否建立成功
    this.isConnect = false // 是否已經連線
    this.isInitiative = false // 是否主動斷開
    this.heartbeatInterval = interval // 心跳檢測間隔
    this.heartbeatTimer = null // 心跳檢測定時器
    this.reconnectTimer = null // 斷線重連定時器
    this.socketExamples = null // websocket例項
    this.againTime = 3 // 重連等待時間(單位秒)
  }

  // 初始化websocket連線
  initSocket() {
    const _this = this
    this.socketExamples = uni.connectSocket({
      url: _this.url,
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        _this.isCreate = true
        console.log(res)
      },
      fail: (rej) => {
        console.error(rej)
        _this.isCreate = false
      }
    })
    this.createSocket()
  }

  // 建立websocket連線
  createSocket() {
    console.log('WebSocket 開始初始化')
    if (this.isCreate) {
      // 監聽 WebSocket 連線開啟事件
      try {
        this.socketExamples.onOpen(() => {
          console.log('WebSocket 連線成功')
          this.isConnect = true
          clearInterval(this.heartbeatTimer)
          clearTimeout(this.reconnectTimer)
          // 開啟心跳檢測
          this.heartbeatCheck()
        })
        // 監聽 WebSocket 接受到伺服器的訊息事件
        this.socketExamples.onMessage((res) => {
          console.log('收到訊息')
          uni.$emit('message', res)
        })
        // 監聽 WebSocket 連線關閉事件
        this.socketExamples.onClose(() => {
          console.log('WebSocket 關閉了')
          this.isConnect = false
          this.reconnect()
        })
        // 監聽 WebSocket 錯誤事件
        this.socketExamples.onError((res) => {
          console.log('WebSocket 出錯了')
          console.log(res)
          this.reconnect()
        })
      } catch (error) {
        console.warn(error)
      }
    } else {
      console.warn('WebSocket 初始化失敗!')
    }
  }

  // 傳送訊息
  sendMsg(value) {
    const param = JSON.stringify(value)
    return new Promise((resolve, reject) => {
      this.socketExamples.send({
        data: param,
        success() {
          console.log('訊息傳送成功')
          resolve(true)
        },
        fail(error) {
          console.log('訊息傳送失敗')
          reject(error)
        }
      })
    })
  }

  // 開啟心跳檢測
  heartbeatCheck() {
    console.log('開啟心跳')
    this.data = { state: 1, method: 'heartbeat' }
    this.heartbeatTimer = setInterval(() => {
      this.sendMsg(this.data)
    }, this.heartbeatInterval * 1000)
  }

  // 重新連線
  reconnect() {
    // 停止傳送心跳
    clearInterval(this.heartbeatTimer)
    clearTimeout(this.reconnectTimer)
    // 如果不是人為關閉的話,進行重連
    if (!this.isInitiative) {
      this.reconnectTimer = setTimeout(() => {
        this.initSocket()
      }, this.againTime * 1000)
    }
  }

  // 關閉 WebSocket 連線
  closeSocket(reason = '關閉') {
    const _this = this
    this.socketExamples.close({
      reason,
      success() {
        _this.data = null
        _this.isCreate = false
        _this.isConnect = false
        _this.isInitiative = true
        _this.socketExamples = null
        clearInterval(_this.heartbeatTimer)
        clearTimeout(_this.reconnectTimer)
        console.log('關閉 WebSocket 成功')
      },
      fail() {
        console.log('關閉 WebSocket 失敗')
      }
    })
  }
}

export default webSocketClass

3,使用

直接例項化封裝的socket類,呼叫初始化方法就行了,當收到訊息的時候,會觸發$emit事件,只需要使用$on監聽message事件就行。

3.1,初始化

import WebSocketClass from '../../utils/webSocket'
const app = getApp()

onLoad() {
  app.globalData.socketObj = new WebSocketClass('wss://www.baidu.com', 90)
  app.globalData.socketObj.initSocket()
}

3.2,傳送訊息

methods: {
  sendMessage() {
    const param = { value: '我是一個訊息' }
    app.globalData.socketObj.sendMsg(param)
  }
}

3.3,接收訊息

// 開啟監聽
onLoad() {
  uni.$on('message', this.getMessage)
},
// 頁面解除安裝時取消監聽
onUnload() {
  uni.$off('message', this.getMessage)
},
methods: {
  // 接收到訊息的回撥
  getMessage(msg) {
    console.log(msg)
  }
}

如果看了覺得有幫助的,我是@鵬多多,歡迎 點贊 關注 評論;END


PS:在本頁按F12,在console中輸入document.querySelectorAll('.diggit')[0].click(),有驚喜哦


公眾號

往期文章

個人主頁