ソースを参照

添加websocket

achao 3 年 前
コミット
a9a16f8d4f

+ 1 - 0
src/api/common/index.js

@@ -101,3 +101,4 @@ export const API_POST_DELETEFILES = `/appendix/api/deleteFiles`
 export const API_POST_OTHERUPLOADFILES = `/appendix/api/uploadFiles`
 //获取公司下拉列表
 export const API_GET_API_COMPLIST = `/commonUser/getComp`
+export const API_GET_ADMINID = `/commonUser/api/onOpen`

+ 73 - 0
src/global.js

@@ -0,0 +1,73 @@
+import Vue from 'vue'
+import store from '@/vendors/vuex'
+// import router from './router'
+// 2.新创建一个vue实例
+const v = new Vue()
+export default {
+  ws: {},
+  websocket: '',
+  setWs: function(newWs) {
+    this.ws = newWs
+  },
+  whetherWebSocket: function() {
+    var that =this
+    debugger
+    if (store.getters.adminId!='') {
+      if ('WebSocket' in window) {
+        if (process.env.NODE_ENV === 'production') {
+          that.websocket = new WebSocket('wss://www.zthymaoyi.com/wss/websocket/' + store.getters.adminId)
+        }
+        else {
+          that.websocket = new WebSocket('ws://localhost:3000/')
+        }
+        that.initWebSocket()
+      } else {
+        alert('当前浏览器不支持websocket')
+      }
+    }
+  },
+  initWebSocket: function() {
+    // 连接错误
+    this.websocket.onerror =evt => {
+      console.log('WebSocket连接发生错误   状态码:' + this.websocket.readyState)
+    }
+    // 连接成功
+    this.websocket.onopen = evt => {
+      console.log('WebSocket连接成功    状态码:' + this.websocket.readyState)
+    }
+    // 收到消息的回调
+    this.websocket.onmessage = event => {
+      // 根据服务器推送的消息做自己的业务处理
+      console.log('服务端返回:' + event.data)
+      var msg = event.data.split('$')
+      var that = this
+      // document.getElementsByClassName('app-container').reload()
+      v.$notify.warning({
+        title: '新消息提醒',
+        message: msg[0],
+        duration: 0,
+        onClick() {
+          this.$router.push({
+            path: msg[1] }) // 你要跳转的路由 还可以传参 当然也可以通过其他方式跳转
+        }
+      })
+      // console.log(router)
+      var currentPage = this.$router.history.current.path
+      console.log(currentPage, 'currentPage')
+      this.$router.push({ path: '/' })
+      console.log('执行成功1')
+      this.$router.push({ path: currentPage,
+        query: {
+          params: Date()
+        }})
+      console.log('执行成功')
+    }
+    // 连接关闭的回调
+    this.websocket.onclose = evt => {
+      console.log('WebSocket连接关闭    状态码:' + this.websocket.readyState)
+    }
+
+    // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
+    window.onbeforeunload = this.onbeforeunload
+  }
+}

+ 2 - 0
src/main.js

@@ -28,6 +28,8 @@ Vue.prototype.WAREHOUSE = Warehouse.houseName
 Vue.prototype.common = Warehouse
 import axios from "axios";
 Vue.prototype.$axios = axios;
+import global from './global.js'
+Vue.prototype.global = global
 // 初始化vue-amap
 // AMap.initAMapApiLoader({
 //   // 高德key

+ 3 - 1
src/model/home/index.js

@@ -3,7 +3,8 @@ import { appRx } from '../defalutConfig/indexRx'
 import {
   API_GET_GETFILELIST,
   API_GET_GETCURRENTUSERINFO,
-  API_GET_GETSTAFFHOMESHOWLIST
+  API_GET_GETSTAFFHOMESHOWLIST,
+  API_GET_ADMINID
 } from '@/api/common'
 import { API_GET_NOTICE_QUERY_NOTICENUMBER } from '@/api/V2/notice'
 
@@ -26,3 +27,4 @@ export const getCurrentUserInfo = appRx.get(API_GET_GETCURRENTUSERINFO, errorCat
 
 export const getStaffHomeShowList = appRx.get(API_GET_GETSTAFFHOMESHOWLIST, errorCatcher, errorHandle, filter)
 export const gChartsData = appRx.get(API_GET_GETCHARTSDATA, errorCatcher, errorHandle, filter)
+export const getAdminId = appRx.get(API_GET_ADMINID, errorCatcher, errorHandle, filter)

+ 1 - 0
src/store/getters.js

@@ -60,6 +60,7 @@ const getters = {
   // 船端是否弹出框
   scheduleState: state => state.user.scheduleState,
   isTrainDialog: state => state.user.isTrainDialog, // 新手训练营弹框显示
+  adminId: state => state.app.adminId, 
 
 }
 export default getters

+ 11 - 2
src/store/modules/user.js

@@ -4,6 +4,7 @@ import { getNoviceGuideData, findVesselSysVersion, getStaffHomeShowList } from '
 import { setToken, getCompanyId, clearStorage } from '../../utils/auth'
 import { resetRouter, asyncRoutes } from '../../router'
 import notification from '../../notification'
+import Cookies from 'js-cookie'
 import {
   setStore,
 } from '@/utils/store'
@@ -22,7 +23,8 @@ const state = {
   guideInfo: {},
   isTrainDialog: '',
   userInfo: '',
-  userSetting: ''
+  userSetting: '',
+  adminId: Cookies.get('adminId') || ''
 }
 
 const getters = {
@@ -74,6 +76,10 @@ const mutations = {
   SET_USERSETTING: (state, params) => {
     state.userSetting = params
   },
+  SET_ADMINID: (state, adminId) => {
+    state.adminId = adminId
+    Cookies.set('adminId', adminId)
+  }
 }
 
 const actions = {
@@ -281,7 +287,10 @@ const actions = {
   async changeVesslBank({ commit, dispatch, state }, showVal) {
     await updateShowInfo(showVal).toPromise()
     dispatch('toSetShow', { userId: localStorage.getItem('ws-pf_userId') })
-  }
+  },
+  setAdminId({ commit }, adminId) {
+    commit('SET_ADMINID', adminId)
+  },
 }
 
 export default {

+ 62 - 1
src/views/home/index.vue

@@ -162,7 +162,8 @@
     noticeNumber,
     queryCircularManagementReceiveList,
     getStaffHomeShowList,
-    gChartsData
+    gChartsData,
+    getAdminId
   } from '@/model/home/index'
   import {
     getUserVesselList,
@@ -327,6 +328,24 @@
       },
 
     },
+    activated(){debugger
+           getAdminId().toPromise().then(response => {debugger
+                this.loading = false
+                // WebSocket
+                this.$store.dispatch('setAdminId', response.data.data)
+                if ('WebSocket' in window) {
+                  if (process.env.NODE_ENV === 'production') {
+                    this.websocket = new WebSocket('wss://www.zthymaoyi.com/wss/websocket/' + response.data.data)
+                  }
+                  else {
+                    this.websocket = new WebSocket('ws://localhost:8080/websocket/' + response.data.data)
+                  }
+                  this.initWebSocket()
+                } else {
+                  alert('当前浏览器不支持websocket')
+                }
+              })
+    },
     async created() {
       //获取快捷路口列表
       this.getRouteList()
@@ -416,6 +435,48 @@
           this.number.news = news
         })
       },
+         initWebSocket () {
+      // 连接错误
+      this.websocket.onerror = this.setErrorMessage
+      // 连接成功
+      this.websocket.onopen = this.setOnopenMessage
+
+      // 收到消息的回调
+      this.websocket.onmessage = this.setOnmessageMessage
+
+      // 连接关闭的回调
+      this.websocket.onclose = this.setOncloseMessage
+
+      // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
+      window.onbeforeunload = this.onbeforeunload
+    },
+    setErrorMessage () {
+      console.log('WebSocket连接发生错误   状态码:' + this.websocket.readyState)
+    },
+    setOnopenMessage () {
+      console.log('WebSocket连接成功    状态码:' + this.websocket.readyState)
+    },
+    setOnmessageMessage (event) {
+      // 根据服务器推送的消息做自己的业务处理
+      console.log('服务端返回:' + event.data)
+      var msg = event.data.split('$')
+      var that = this
+      this.$notify.warning({
+        title: '新消息提醒',
+        message: msg[0],
+        duration: 0,
+        onClick() {
+          that.$router.push({
+            path: msg[1] }) // 你要跳转的路由 还可以传参 当然也可以通过其他方式跳转
+        }
+      })
+      var currentPage = that.$router.history.current.path
+      that.$router.push({ path: '/' })
+      that.$router.push({ path: currentPage })
+    },
+    setOncloseMessage () {
+      console.log('WebSocket连接关闭    状态码:' + this.websocket.readyState)
+    },
       //跳转
       contract(index){
          if(index == 0){