Vue中如何使用websocket

2023-05-16

1新建文件夹 socket.js(目录自己看着办,可以放lib或者utils)

import Vue from 'vue'
const ReconnectingWebSocket = require('@/api/webSocket/reconnecting-websocket.min.js') // https://github.com/joewalnes/reconnecting-websocket

/**
 * @param {params.userId} string 用户id
 */
export default function initWebSocket (params) { // 初始化weosocket
  let port = '8888' //测试:端口
  let uri = '192.168.**.**' // 测试 地址
  let url = `ws://${uri}:${port}/${params.userId}`

  if ('WebSocket' in window) {
    Vue.prototype.$socket = new ReconnectingWebSocket(url, null, {
      debug: false, // console.debug()记录调试消息
      automaticOpen: true, // 实例化后立即连接 ws.open()和 ws.close() 可以手动管理
      reconnectInterval: 1000, // 重新连接延迟时间
      maxReconnectInterval: 2000, // 等待重连最长时间
      reconnectDecay: 1, // 延迟重连时间的增加率
      timeoutInterval: 3000, // 在关闭和重试之前等待连接成功的最长时间
      maxReconnectAttempts: null, // 最大尝试重连次数
      binaryType: 'blob' // 二进制类型
    })

    Vue.prototype.$socket.sendObj = (data) => {
      Vue.prototype.$socket.send(JSON.stringify(data))
    }
  } else {
    alert('您的浏览器不支持 WebSocket!')
  }
}

2 reconnecting-websocket.min.js下载地址 https://github.com/joewalnes/reconnecting-websocket

3如何去使用,首先上面的userId是用户登录之后返回的数据,用于建立websocket连接,login.vue中this.$cookie.set(userId:data.userId)而来的

目前我是在app.vue中去全局引用通过websocket.onmessage去监听并改变store中定义的数据,代码如下

import socket from '@/api/socket'  //更具你自己的文件去引入之前新建的js

//钩子函数去初始化socket
created () {
      let userId = this.$cookie.get('userId')//获取登陆后的userId
      userId && socket({ userId: userId })
      userId && this.bindSocketHandle() // 强制刷新浏览器后重新连接socket并绑定事件
     },

bindSocketHandle方法如下

  methods: {
   bindSocketHandle () {
        this.$socket.onmessage = this.getMessageInfo  //之前vue中原型已经注册所以可以直接使用
        this.$socket.onclose = this.socketClose  //关闭后的方法我就不举例了
        this.$socket.onerror = this.socketError   //错误时调用的方法我就不举例了
      },
        getMessageInfo({ data }){
            let msg = JSON.parse(data)  //后端返回的是json数据,需要转换
        switch (msg.uri) {
          case '11':
            this.$store.commit('socket/UPDATE_SYSPUSHMSG', msg.data)//也可以试试用vuestore的mapActions
            break
          case '222':
            this.$store.commit('socket/UPDATE_COUNTUNREAD', msg.data)
            break
    
        }
                
      },
            
}

 

store里面我就不举例子了,最后提醒只要监听store state的数据是否改变(mapState)来进行对应的操作,可以放在computed里面,watch你喜欢也行吧,你喜欢就好.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vue中如何使用websocket 的相关文章

随机推荐