一、使用步骤
data(){
return{
websock: null, //建立的连接
lockReconnect: false, //是否真正建立连接
timeout: 20 * 1000, //20秒一次心跳
timeoutObj: null, //心跳心跳倒计时
serverTimeoutObj: null, //心跳倒计时
timeoutnum: null, //断开 重连倒计时
}
},
mounted(){
this.iniWebSocket();
},
methods: {
iniWebSocket() {
//初始化websocket
const wsuri =
"websocket地址";
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;
},
reconnect() {
//重新连接
var that = this;
if (that.lockReconnect) {
return;
}
that.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
that.timeoutnum && clearTimeout(that.timeoutnum);
that.timeoutnum = setTimeout(function () {
//新连接
that.iniWebSocket();
that.lockReconnect = false;
}, 1000);
},
reset() {
//重置心跳
var that = this;
//清除时间
clearTimeout(that.timeoutObj);
clearTimeout(that.serverTimeoutObj);
//重启心跳
that.start();
},
start() {
//开启心跳
var self = this;
self.timeoutObj && clearTimeout(self.timeoutObj);
self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
self.timeoutObj = setTimeout(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息
if (self.websock.readyState == 1) {
//如果连接正常
self.websock.send('ping!' + this.userData.userId);
} else {
//否则重连
self.reconnect();
}
self.serverTimeoutObj = setTimeout(function () {
//超时关闭
self.websock.close();
}, self.timeout);
}, self.timeout);
},
websocketonopen() {
//连接建立之后执行send方法发送数据
let actions = { test: "发送数据" };
this.websocketsend(JSON.stringify(actions));
console.log("连接");
//开启心跳
this.start();
},
websocketonerror() {
//连接建立失败重连
this.iniWebSocket();
this.reconnect();
console.log("重新连接");
},
websocketonmessage(e) {
//数据接收
const redata = JSON.parse(e.data);
console.log("数据接收", redata);
//if (e.data !== 'pang!') {
//this.$notify({
//title: this.$moment().format('YYYY.MM.DD HH:mm'),
//message: e.data,
//position: 'bottom-right',
//customClass: 'socketMsg',
//onClick: () => {
//if (this.$route.path === '/notification') {
// this.$bus.emit('updateList')
//} else {
// this.$router.push('/notification')
// }
// }
// })
this.getUnReadList()
}
this.reset();
},
websocketsend(Data) {
//数据发送
this.websock.send('ping!' + Data)
},
websocketclose(e) {
//关闭
console.log("断开连接", e);
//重连
this.reconnect();
},
}
beforeDestroy() {
this.websock.onclose()
}