websocket.js
//这里需要引入vuex
// import store from '../index';
import store from '@/store/index.js'
// let wshttpurl = process.env.VUE_APP_BASE_API
// var wsurl = `ws:${wshttpurl}:8999`
var wsurl = `ws://192.168.1.74:8848/ws`
console.log('这是获取到的本地ws地址', wsurl);
console.log('这是ws地址', wsurl);
let wsConnection = {
$ws: null,
lockReturn: false,
timeout: 6 * 1000 * 5,
timeoutObj: null,
timeoutNum: null,
serverTimeoutObj: null,
//初始化webSocket长连接
initWebSocket: function () {
this.$ws = new WebSocket(wsurl);//写入地址
this.$ws.onopen = this.wsOpen;
this.$ws.onclose = this.wsClose;
this.$ws.onmessage = this.wsMsg;
this.$ws.onerror = this.wsError;
},
//打开websocket
wsOpen: function (e) {
console.log('socket打开了', e);
//开始websocket心跳
// this.send('hello,pzj')
wsConnection.startWsHeartbeat();
console.log("websocket连接成功");
// this.$ws.send('hello')
},
wsClose: function (e) {
console.log("websocket连接关闭", e);
// console.log('######',store.statistics);
},
wsMsg: function (msg) {
//每次接收到服务端消息后 重置websocket心跳
wsConnection.resetHeartbeat();
console.log('这是消息', msg)
let data = msg
store.commit('SET_ALLDATA', data);
console.log("sto", store.state.dataview);
// console.log('######',store.state.statistics.alldata
// );
//服务端发送来的消息存到vuex
// console.log(msg.data, '@@@@@')
// if (msg.data) {
// let data = JSON.parse(msg.data)
// if (data.type == 'OtherInfoUp') {
// // console.log(data, '@@@@@@@@@@@@@@@');
// }
// store.commit('webSocketmsg', data)
// }
},
wsError: function (err) {
console.log("websocket连接错误", err);
// store.commit('statistics/SET_ALLDATA', {name: '张三'});
// console.log(err, 'ws error');
wsConnection.reconnect()
},
//重启websocket
reconnect: function () {
let _this = this;
if (_this.lockReturn) {
return;
}
_this.lockReturn = true;
_this.timeoutNum && clearTimeout(_this.timeoutNum);
_this.timeoutNum = setTimeout(function () {
_this.initWebSocket();
_this.lockReturn = false;
}, 3000);
},
startWsHeartbeat: function () {
let _this = this;
_this.timeoutObj && clearTimeout(_this.timeoutObj);
_this.serverTimeoutObj && clearTimeout(_this.serverTimeoutObj);
_this.timeoutObj = setInterval(function () {
//判断websocket当前状态
if (_this.$ws.readyState != 1) {
_this.reconnect()
}
}, _this.timeout);
},
//重置websocket心跳
resetHeartbeat: function () {
let _this = this;
clearTimeout(_this.timeoutObj);
clearTimeout(_this.serverTimeoutObj);
_this.startWsHeartbeat()
}
};
//抛出websocket对象
export default wsConnection
main.js
import createSocket from '@/utils/websocket.js'
Vue.prototype.$socket = createSocket