<script>
export default {
name: "listBasePageList",
created() {
this.initWebSocket();
},
methods: {
initWebSocket() {
//输入服务端创建的websoket端口
const wsuri = "ws://172.0.0.1:9999/";
//建立连接
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("heartbeat"); //如果连接正常
} else {
self.reconnect();//否则重连
}
self.serverTimeoutObj = setTimeout(function () {
self.websock.close();//超时关闭
}, self.timeout);
}, self.timeout);
},
websocketonopen() {
this.websocketsend("发送数据"); //连接成功事件 并且告诉服务端已经收到
//提示成功
console.log("连接成功", 3);
//开启心跳
this.start();
},
websocketonerror(e) {
//连接失败事件
//错误
console.log("WebSocket连接发生错误");
//重连
this.reconnect();
},
websocketclose(e) {
//连接关闭事件
//提示关闭
console.log("连接已关闭");
//重连
this.reconnect();
},
websocketonmessage(event) {
//接收服务器推送的信息
//打印收到服务器的内容
console.log("收到服务器信息", event.data);
//收到服务器信息,心跳重置
this.reset();
},
websocketsend(msg) {
this.websock.send(msg);//向服务器发送信息
},
},
};
</script>