1、websocket的封装
uniapp获取websocket返回来的数据可以采用Vuex进行存储

class websocketUtil {
  constructor(url, time) {
  /*
  url 是请求的后端的地址
  time 是心跳包的时间
  */
    this.is_open_socket = false //避免重复连接
    this.url = url //地址
    this.data = null
    //心跳检测
    this.timeout = time //多少秒执行检测
    this.heartbeatInterval = null //检测服务器端是否还活着
    this.reconnectTimeOut = null //重连之后多久再次重连

    try {
      return this.connectSocketInit()
    } catch (e) {
      console.log('catch');
      this.is_open_socket = false
      this.reconnect();
    }
  }

  // 进入这个页面的时候创建websocket连接【整个页面随时使用】
  connectSocketInit () {
    this.socketTask = uni.connectSocket({
      url: this.url,
      success: () => {
        console.log("正准备建立websocket中...");
        // 返回实例
        return this.socketTask
      },
    });
    this.socketTask.onOpen((res) => {
      console.log("WebSocket连接正常!");
      clearTimeout(this.reconnectTimeOut)
      clearTimeout(this.heartbeatInterval)
      this.is_open_socket = true;
      this.start();
      // 注:只有连接正常打开中 ,才能正常收到消息
      this.socketTask.onMessage((res) => {
        const data = JSON.parse(res.data)
        // 可以写业务逻辑,看个人的需求
        if (data.status === 200) {
          store.dispatch("changeUp", data.data)
          const { role } = store.state
          if (role) {
            const info = uni.getStorageSync("info");
            if (role !== JSON.parse(info).role) {
              uni.showModal({
                title: '温馨提示',
                content: '权限发生改变,请重新登录',
                showCancel: false,
                confirmText: '请登录',
                success (res) {
                  if (res.confirm) {
                    uni.removeStorageSync('info')
                    uni.removeStorageSync('access-token')
                    uni.navigateTo({ url: '/pages/auth/login' })
                  }
                }
              })
            }
          }
        }
        console.log(res.data)
      });
    })

    // 这里仅是事件监听【如果socket关闭了会执行】
    this.socketTask.onClose((res) => {
      if (res.code === 1000) {
        this.is_open_socket = true;
      } else {
        this.is_open_socket = false;
      }
      console.log("已经被关闭了", res)
      this.reconnect();
    })
  }

  //发送消息
  send (value) {
    // 注:只有连接正常打开中 ,才能正常成功发送消息
    this.socketTask.send({
      data: value
    });
  }
  //开启心跳检测
  start () {
    this.heartbeatInterval = setInterval(() => {
      this.data = { type: "start" }
      this.send(JSON.stringify(this.data));
      console.log('心跳包');
    }, this.timeout)
  }
  //重新连接
  reconnect () {
    //停止发送心跳
    clearInterval(this.heartbeatInterval)
    //如果不是人为关闭的话,进行重连
    if (!this.is_open_socket) {
      this.reconnectTimeOut = setTimeout(() => {
        this.connectSocketInit();
      }, 3000)
    }
  }
}

module.exports = websocketUtil

2、Vuex的使用
在src下建个文件夹state 存放index.js、state.js 、mutations.js、getters.js、actions.js

import Vue from 'vue'
import Vuex from 'vuex'

import state from './state'
import mutations from './mutations'
import getters from './getters'
import actions from './actions'

Vue.use(Vuex)

const store = new Vuex.Store({
  state,
  mutations,
  getters,
  actions,
})

export default store

state.js存放初始化数据,代码如下:

const state = {
  role: '',
  showDesign: '',
  notifyCount: 0,
  openMusic: ''
}

export default state

actions.js是通过 store.dispatch(“changeUp”, data.data)事件触发,代码如下:

const actions = {
  changeUp (context, data) {
    context.commit('changeUp', data)
  }
}
export default actions

mutations.js是改变state的值,代码如下:

const mutations = {
  changeUp (state, data) {
    state.role = data.role,
      state.showDesign = data.design
    state.notifyCount = data.amount
    state.openMusic = data.open_music
  },
}

export default mutations

getters.js是配合Vue的计算属性使用的,代码如下:

const getters = {
  showDesign (state) {
    return state.showDesign
  },
  notifyCount (state) {
    return state.notifyCount
  },
  openMusic (state) {
    return state.openMusic
  }
}
export default getters

Vue中计算属性(computed)的使用,代码如下:

// 引入Vuex
import { mapGetters } from 'vuex'
  computed: {
    ...mapGetters({
      showDesign: 'showDesign',
      notifyCount: 'notifyCount',
      openMusic: 'openMusic'
    })
  },

mapGetters 的使用请查看

3、页面中的使用代码如下:

// 引入websocket
import websocket from '../../utils/websocket'
  onShow () {
    const urlWss ='ws://127.0.0.1:3000?token=1'
     const wss= new websocket (urlWss, 5000)
  },
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐