import { logAxis } from 'echarts/lib/theme/dark' import { Notification } from 'element-ui' import router from '../../router' import user from './user' const websocket = { state: { // wsUrl: 'ws://198.168.1.113:11307/websocket/', // wsUrl: 'ws://127.0.0.1:8095/websocket/', // wsUrl: 'ws://111.198.10.15:21405/websocket/', wsUrl: 'ws://139.198.18.188:8083/websocket/', websocket: null, wsStatus: false, // websocket连接状态 needRefresh: false // 是否需要刷新数据 }, mutations: { SET_WEBSOCKET: (state, websocket) => { state.websocket = websocket }, SET_WS_STATUS: (state, wsStatus) => { state.wsStatus = wsStatus }, SET_NEED_REFRESH: (state, needRefresh) => { state.needRefresh = needRefresh } }, actions: { // 连接websocket initWebSocket({ commit }) { if (typeof (WebSocket) === 'undefined') { Notification({ title: '提示', message: '当前浏览器无法接收实时信息,请使用谷歌浏览器或360浏览器极速模式!', type: 'warning', duration: 0 }) } else { // 获取token保存到vuex中的用户信息,此处仅适用于本项目,注意删除或修改 // 实例化socket,这里我把用户名传给了后台,使后台能判断要把消息发给哪个用户,其实也可以后台直接获取用户IP来判断并推送 // const socketUrl = websocket.state.wsUrl + user.state.token const socketUrl = websocket.state.wsUrl + user.state.id const socket = new WebSocket(socketUrl) commit('SET_WEBSOCKET', socket) commit('SET_WS_STATUS', true) // 监听socket打开 socket.onopen = function() { console.log('浏览器WebSocket已打开') } // 监听socket消息接收 socket.onmessage = function(msg) { // 设备更新数据结果 const data = JSON.parse(msg.data) console.log('socket返回数据', data) Notification({ title: '导出图片结果', message: data.message, type: 'success', duration: 0 }) } // 监听socket错误 socket.onerror = function() { Notification({ title: '服务器错误', message: '无法接收实时信息,请检查服务器后重新刷新页面', type: 'error', duration: 0 }) } // 监听socket关闭 socket.onclose = function() { console.log('WebSocket已关闭') commit('SET_WS_STATUS', false) } } } } } export default websocket