1. 程式人生 > 其它 >專案中websocket簡單應用

專案中websocket簡單應用

技術標籤:js

參考:

HTML5 WebSocket
WebSocket 教程

<template>
  <div id="app" class="mainContainer">
    <div class="topSide">
      <div class="topRight">
        <span class="timeStr">{{formatTimeStr}}</span>
        <span class="secondStr">{{formatSecStr}}</span>
        <span class="dateStr">{{formatDateStr}}</span>
        <span class="weekStr">周{{dayStr}}</span>
        <span v-if="websocketError" style="color: red">!</span>
      </div>
    </div>
    <div class="bottomSide">
      <router-view></router-view>
    </div>
  </div>
</template>
export default {
  name: 'App',
  data() {
    return {
      runTimeShow: new Date().getTime(),
      runSeconds: 0,
      websock: null,
      todayRefresh: true,
      websocketError: false
    }
  },
  computed: {
    formatTimeStr() {
      let dateObj = new Date(this.runTimeShow)
      let hours = dateObj.getHours();
      //凌晨四點做一次全域性重新整理
      if (hours == 4 && this.todayRefresh) {
        this.initData();
        this.todayRefresh = false;
      }
      //零點設定重新整理欄位為true
      if (hours == 0) {
        this.todayRefresh = true;
      }
      if (hours < 10) {
        hours = '0' + hours
      }
      let minu = dateObj.getMinutes();
      if (minu < 10) {
        minu = '0' + minu
      }
      let seco = dateObj.getSeconds();
      if (seco < 10) {
        seco = '0' + seco
      }
      return hours + ':' + minu + ':' + seco;
    },
    formatSecStr() {
      if (this.runSeconds < 10) {
        return this.runSeconds
      }
    },
    formatDateStr() {
      let dateObj = new Date(this.runTimeShow)
      let year = dateObj.getFullYear();
      let month = dateObj.getMonth() + 1;
      let dateStr = dateObj.getDate();
      if (month < 10) {
        month = '0' + month
      }
      if (dateStr < 10) {
        dateStr = '0' + dateStr
      }
      return year + '-' + month + '-' + dateStr;
    },
    dayStr() {
      let dateObj = new Date(this.runTimeShow);
      let dayNum = dateObj.getDay();
      switch (dayNum) {
        case 0:
          return '日';
          break;
        case 1:
          return '一';
          break;
        case 2:
          return '二';
          break;
        case 3:
          return '三';
          break;
        case 4:
          return '四';
          break;
        case 5:
          return '五';
          break;
        case 6:
          return '六';
          break;
      }
    }
  },
  created() {
    this.initTimeRun();
    this.initData();
    this.initWebSocket();
  },
  destroyed() {
    this.websock.close() //離開路由之後斷開websocket連線
  },
  methods: {
    initWebSocket() { //初始化weosocket
      const wsuri = "xxxxxxxxx";  // url地址
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() { //連線建立之後執行send方法傳送資料
      let actions = { "sessionId": "SCREEN", "event": "LOGIN", "body": "xxx11" };
      this.websock.send(JSON.stringify(actions));
      this.checkWebSocket();
    },
    websocketonerror() { //連線建立失敗重連
      console.log('連線失敗,請稍後再試');
      this.websocketError = true;
    },
    websocketonmessage(e) { //資料接收
      const redata = JSON.parse(e.data);
      console.log('連結成功!',redata.event);
      switch (redata.event) {
        case 'task':
          this.$store.dispatch('getTaskData');
          this.$store.dispatch('getWorkData');
          break;
        case 'bug':
          this.$store.dispatch('getBugData');
          break;
        case 'team':
          this.$store.dispatch('getStaffData');
        case 'OFF_LINE':
          console.log('重新連結!', e);
          this.initWebSocket();
          break;
      }
    },
    websocketclose(e) { //關閉
      console.log('斷開連線!', e);
      this.websocketError = true;
    },
    initTimeRun() {
      setInterval(() => {
        this.runSeconds++;
        if (this.runSeconds == 10) {
          this.runTimeShow = new Date().getTime();
          this.runSeconds = 0;
        }
      }, 100)
    },
    checkWebSocket() {
      setInterval(() => {
        let actions = { "sessionId": "SCREEN", "event": "HEART_BEAT", "body": "xxx11" };
        this.websock.send(JSON.stringify(actions));
      }, 10000)
    },
    initData() {
      this.$store.dispatch('getBugData');
      this.$store.dispatch('getTaskData');
      this.$store.dispatch('getWorkData');
      this.$store.dispatch('getStaffData');
    }
  }
}
</script>

computed裡面的方法主要是為了實現實時時間
在這裡插入圖片描述

websocket一系列方法實現:頁面其他部分:實時資料的獲取