vue 访问ws websocket请求访问

vue yekong

数据大屏开发中,需要监听实时消息,消息是使用的,最新的项目中获取ws数据的方法:vue项目中请求WebSocket获取数据

公共方法

function getSocket(url, params, callback) {
  let socket;

  if (typeof (WebSocket) === 'undefined') {
    console.log('您的浏览器不支持WebSocket');
  } else {
    console.log('您的浏览器支持WebSocket');

    // 初始化 WebSocket 对象,指定要连接的服务器地址与端口建立连接
    socket = new WebSocket(url);

    // 打开事件
    socket.onopen = function () {
      console.log('Socket 已打开');
      socket.send(params);
    };

    // 获得消息事件
    socket.onmessage = function (msg) {
      // 发现消息进入, 开始处理前端触发逻辑
      callback(msg, socket);
    };

    // 关闭事件
    socket.onclose = function () {
      console.log('Socket 已关闭');
    };

    // 发生了错误事件
    socket.onerror = function () {
      console.log('Socket 发生了错误,请刷新页面');
      // 此时可以尝试刷新页面
    };
  }
}

export {
  getSocket
};

访问ws接口

/**
* @Author: 858834013@qq.com
* @Name: message
* @Date: 2022-03-05
* @Desc:
*/
<template>
  <div>

  </div>
</template>

<script>
import {getSocket} from '@/utils/websocket.js'
import {maxScreen, mqttAccessToken} from "@/api/api/user";

export default {
  data() {
    return {
      wsData: {}, // 保存 websocket 数据对象
      form: { // 表单
        name: '',
        age: ''
      }
    }
  },
  beforeDestroy() {
    this.wsData.close(); // 关闭 websocket
  },
  created() {
  },
  mounted() {
    this.mqttAccessToken()
  },
  methods: {
    mqttAccessToken() {
      var that = this;
      mqttAccessToken({}).then(res => {
        this.totalCount = res.totalCount
      }).catch(err => {

      })
    },
    // 获取数据
    getSocketData() {
      let params = this.form;
      console.log(123)
      getSocket(
        `ws://81.69.19.6:8083/mqtt`,
        JSON.stringify(params),
        (data, ws) => {
          console.log(data, ws);

          // 保存数据对象, 以便发送消息
          this.wsData = ws;
        }
      );
    },

    // 发送数据
    sendSocketData() {
      let params = this.form;
      params.name = 'xx';
      params.age = '18';
      this.wsData.send(JSON.stringify(params));
    }
  }
}
</script>
<style lang="scss" scoped>

</style>

实例ws接口 (心跳)

定时请求ws当接口返回的数据类型有变化后,请求对应的接口

import {getSocket} from "@/utils/utils";

export default {
  data() {
    return {
      selDate: '',
      id: this.$route.query.id,
      enterpriseId: this.$route.query.enterpriseId,
      signStatus: 0,
      list: [],
      showStatus: 0,
      weiDaoNum: 0,
      yiDaoNum: 0,
      yiTuiNum: 0,
      websock: null,
      ws: null,
      time: null,
      data: {
        deptName: '',
        title: '',
      }
    }
  },
  components: {pageHeader, userInfo, goback},
  created() {
  },
  computed: mapGetters(['classData']),
  mounted() {
    var that = this;
    this.getSocketData()
    this.time = window.setInterval(() => {
      that.sendSocketData()
    }, 3000)
  },
  //销毁定时
  destroyed() {
    clearInterval(this.time);
  },
  methods: {
    goback() {
      this.$router.go(-1)
    },
    // 获取数据
    getSocketData() {
      var that = this;
      let params = {msgType: "USER_REGISTER", data: {fkId: this.id, nettyType: 'BIGCOURSE'}};
      console.log(123)
      getSocket(
        `websocket`,
        JSON.stringify(params),
        (data, ws) => {
          console.log(data, ws);
          console.log(JSON.parse(data.data));
          // 保存数据对象, 以便发送消息
          判断值是否有变化有变化则请求接口
          if (JSON.parse(data.data).msgType == 'UPDATE_SIGN') {
            that.getdata()
          }
          this.wsData = ws;
          // this.sendSocketData()
        }
      );
    },

    // 发送数据
    sendSocketData() {
      var that = this;
      var data = {msgType: "HEARTBEAT"}
      if (this.wsData) {
        this.wsData.send(JSON.stringify(data));
      }
    }
  },
}
喜欢