vue项目使用websocket连接
封装websocket
vuex中
state: {
permissions: false,
url: '', // ws地址
//ws参数
path: '',
ws: null,//建立的连接
lockReconnect: false,//是否真正建立连接
timeout: 58*1000,//58秒一次心跳
timeoutObj: null,//心跳心跳倒计时
serverTimeoutObj: null,//心跳倒计时
timeoutnum: null,//断开 重连倒计时
},
在utils中新建wsconnect.js文件
import axios from "axios";
import store from "@/store";
//websocket
function initWebpack(){
var url = store.state.url
store.state.ws = new WebSocket(url);
store.state.ws.onopen = onopen;
store.state.ws.onmessage = onmessage;
store.state.ws.onclose = onclose;
store.state.ws.onerror = onerror;
}
function onopen() {
console.log("连接websocket");
var params = '{"reqtype":"Query","action":"allexts"}'
store.state.ws.send(params)
start();
}
function onmessage(e) {
console.log('接收数据',e)
//处理数据的地方
}
function onclose(e) {
console.log('websocket 断开: ',e);
}
function onerror(e) {
console.log("出现错误");
//重连
reconnect();
}
function reconnect() {//重新连接
var that = store.state;
if(that.lockReconnect) {
return;
}
that.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
that.timeoutnum && clearTimeout(that.timeoutnum);
that.timeoutnum = setTimeout(function () {
//新连接
initWebpack();
that.lockReconnect = false;
that.isFirstGet = true
},5000);
}
function reset(){//重置心跳
var that = store.state;
//清除时间
clearTimeout(that.timeoutObj);
clearTimeout(that.serverTimeoutObj);
//重启心跳
start();
}
function start(){ //开启心跳
console.log('开启心跳');
var self = store.state;
self.timeoutObj && clearTimeout(self.timeoutObj);
self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
self.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
if (self.ws.readyState === 1) {//如果连接正常
self.ws.send(heartbeat); //心跳包格式需要自己确定
}else{//否则重连
reconnect();
}
self.serverTimeoutObj = setTimeout(function() {
//超时关闭
self.ws.close();
reconnect()
}, self.timeout);
}, self.timeout)
}
export default {
initWebpack,
onmessage,
onclose,
onopen,
onerror
}
注册wsconnect
main.js中
import wsConnect from "@/utils/wsConnect";
Vue.prototype.$ws = wsConnect
初始化连接
app.vue挂载之后直接初始化ws链接
mounted() {
this.$ws.initWebpack()
}
发送消息数据
this.$store.state.ws.send(msg)