websocket

作者: 一名有马甲线的程序媛 | 来源:发表于2019-01-10 20:44 被阅读4次
  1. 新建websocket.js

import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import { mapState } from 'vuex';
export default {
  data () {
    return {
    };
  },
  computed: {
    ...mapState([
      'vuexStompClient',
      'vuexTimerSuccess',
      'vuexTimerErr',
      'flag',
    ]),
  },
  methods: {
    /**
     * websocket
     */
    getWebsocket (callback) {
      this.$http.get(this.$serverConfig.baseUrl + '/mits-master/v1/application/query-value-by-cid?consultationId=' + this.consultationId).then(({ subCode, data }) => {
        if (subCode === 'SUCCESS') {
          this.connection();
          typeof callback === 'function' && callback();
        } else {
          this.$message({
            type: 'error',
            message: '此报告处于编辑中,请刷新重试!'
          });
        }
      });
    },

    // 连接 后台
    connection () {
      // 建立连接对象
      let socket = new SockJS(this.$serverConfig.webSocketUrl + '/p-to-p');

      // 获取STOMP子协议的客户端对象
      this.$store.commit('chgVuexStompClient', Stomp.over(socket));

      console.log('this.vuexStompClient', this.vuexStompClient);

      // 向服务器发起websocket连接
      this.vuexStompClient.connect({}, (frame) => {
        console.log('Connected: ' + frame);
        if (this.vuexTimerSuccess) {
          clearInterval(this.vuexTimerSuccess);
        }
        let that = this;
        that.connectSuccess();
        this.$store.commit('chgVuexTimerSuccess', setInterval(() => {
          console.log('进入循环');
          that.connectSuccess();
        }, 5000));

        // 接收后台返回消息
        console.log('this.vuexStompClient', this.vuexStompClient.subscribe);
        this.vuexStompClient.subscribe('/user/' + this.consultationId + '/topic/private-topic', (greeting) => {
          console.log('greeting', greeting);
          if (JSON.parse(greeting.body).subCode !== 'SUCCESS') {
            this.$message({
              type: 'error',
              message: '由于网络断开,此检查已被占有,请刷新重试!'
            });
            this.disconnect();
          } else {
            if (JSON.parse(greeting.body).data === '0') {
              if (!this.flag) {
                this.$alert('此检查已被您在其他端暂存,请刷新重试!')
                  .then(_ => {
                    this.$store.commit('chgReportNeedRefresh', true);
                  });
              }
            } else if (JSON.parse(greeting.body).data === '1') {
              if (!this.flag) {
                this.$alert('此检查已被您在其他端提交,请刷新重试!')
                  .then(_ => {
                    this.$store.commit('chgReportNeedRefresh', true);
                  });
              }
            }
          }
        }, {});
      }, (err) => {
        // 连接发生错误时的处理函数
        console.log('失败');
        console.log(err);
        this.disconnect();
        if (this.vuexTimerErr) {
          clearInterval(this.vuexTimerErr);
        }
        let that = this;
        this.$store.commit('chgVuexTimerErr', setInterval(() => {
          that.connection();
        }, 5000));
      });
    },

    // 成功连接websocket
    connectSuccess () {
      // 向后台发送数据
      this.vuexStompClient.send('/app/message', {}, JSON.stringify(
        {
          'userId': localStorage.getItem('userId_' + this.role),
          'consultationId': this.consultationId,
        }));
    },

    // 断开连接
    disconnect () {
      console.log('this.vuexStompClient', this.vuexStompClient);
      // 通知后台断开
      this.$http.get(this.$serverConfig.baseUrl + '/mits-master/v1/application/update-value-by-cid/' + this.consultationId).then(({ subCode, data }) => {
        console.log('通知后台断开', subCode, data);
      });

      // 前端断开
      if (this.vuexStompClient) {
        this.vuexStompClient.disconnect();
        if (this.vuexTimerSuccess) {
          clearInterval(this.vuexTimerSuccess);
        }
        if (this.vuexTimerErr) {
          clearInterval(this.vuexTimerErr);
        }
      }
    },
  },
};

  1. 在vuex中设全局变量
state: {
    // 是否刷新报告单
    reportNeedRefresh: false,

    // websocket
    vuexStompClient: '',
    vuexTimerSuccess: '',
    vuexTimerErr: '',
    flag: false, // 暂存是否为本人
}
mutations: {
    chgReportNeedRefresh (state, bol) {
      state.reportNeedRefresh = bol;
    },

    chgVuexStompClient (state, vuexStompClient) {
      state.vuexStompClient = vuexStompClient;
    },

    chgVuexTimerSuccess (state, vuexTimerSuccess) {
      state.vuexTimerSuccess = vuexTimerSuccess;
    },

    chgVuexTimerErr (state, vuexTimerErr) {
      state.vuexTimerErr = vuexTimerErr;
    },

    chgFlag (state, flag) {
      state.flag = flag;
    },
}
  1. 应用场景:
  • 专家端:点击“编辑/审核报告单”,调用this.getWebsocket回调函数,如果返回真,再进入报告单。
    退出调用this.disconnect()
    电脑端、手机端同时登录同一账号,并填写同一报告单,一端先暂存/提交,另一端出提示弹窗“此检查已被您在其他端提交,请刷新重试!”,点击后刷新报告单页数据。
  • 申请端:点“修改申请单”,调用this.getWebsocket回调函数,如果返回真,再弹出修改申请单弹窗。
    退出调用this.disconnect()

相关文章

网友评论

      本文标题:websocket

      本文链接:https://www.haomeiwen.com/subject/fwrzrqtx.html