<template>
<div></div>
</template>
<script>
export default {
data() {
return {
websock: null,
lockReconnect: false,
timeout: 28 * 1000,
timeoutObj: null,
serverTimeoutObj: null,
timeoutnum: null,
}
},
created() {
this.initWebSocket();
},
destroyed: function () {
this.websocketclose();
},
methods: {
initWebSocket() {
const wsuri ="ws://sms.balabala.com/websocket/" + this.$route.query.telphone
this.websock = new WebSocket(wsuri);
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
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.initWebSocket();
that.lockReconnect = false;
}, 5000);
},
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(
'{"toUserId":"' + self.$route.query.telphone + '"}'
);
console.log("发送消息");
} else {
self.reconnect();
}
self.serverTimeoutObj = setTimeout(function () {
self.websock.close();
}, self.timeout);
}, self.timeout);
},
websocketonopen() {
console.log("连接成功", 3);
this.start();
},
websocketonerror(e) {
console.log("WebSocket连接发生错误");
console.log("Websocket error, Check you internet!");
this.reconnect();
},
websocketclose(e) {
console.log("connection closed (" + e + ")");
console.log("连接已关闭", 3);
this.reconnect();
},
websocketonmessage(event) {
let that = this;
const redata = JSON.parse(event.data);
console.log(redata,"数据接收");
this.reset();
},
websocketsend(msg) {
this.websock.send(msg);
},
},
};
</script>
<style scoped>
</style>
转自www.cnblogs.com/minghan/p/1…