uniapp的websocket的使用

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)
  },
  • 11
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
uniapp使用WebSocket可以通过以下步骤进行操作: 1. 首先,在你的项目中创建一个websocket.js文件,可以放在utils目录下。在这个文件中,你可以定义一个WebSocket类,用于处理WebSocket的连接和消息传输。 2. 在websocket.js文件中,你可以使用uni.connectSocket接口来创建一个WebSocket连接。这个接口返回一个SocketTask对象,你可以使用这个对象来发送和接收消息。 3. 在你的页面中,引入websocket.js文件,并创建一个WebSocket实例。你可以将这个实例挂载到全局的Vue.prototype.$socket上,以便在其他页面中也可以使用。 4. 在页面中,你可以使用this.$socket.send方法来发送消息,传入一个字符串参数作为要发送的内容。 5. 同样地,你可以使用this.$socket.getMessage方法来接收消息。这个方法接受一个回调函数作为参数,当接收到消息时,回调函数会被调用,并传入接收到的消息作为参数。 需要注意的是,在测试环境中,WebSocket的URL可以写成ws://xxx:3100/connect/websocket,而在发布体验版或正式版中,URL应该写成wss://xxx:3100/connect/websocket,以确保安全连接。 总结起来,使用uniappWebSocket可以通过创建WebSocket类、调用uni.connectSocket接口来创建连接、发送和接收消息来实现。具体的代码示例可以参考引用\[1\]中的示例代码。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [uni-app使用websocket(封装、心跳检测、实时信息)](https://blog.csdn.net/m0_60289222/article/details/130315532)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [uniapp APP 端 WebSocket 使用,实现一个简单 WebSocket 工具类](https://blog.csdn.net/sinat_35272898/article/details/122511603)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kjs_pass

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值