跳到主要内容

简单断线重连

前端处理

let lock = false;
let wsClient;

function reConnect() {
if (lock) return;
lock = true;
console.log('正在重连')
setTimeout(function () {
NewClient()
lock = false
}, 2000)
}

// 0: 表示连接尚未建立
// 1: 表示连接已经建立可以通信
// 2: 表示连接正在关闭
// 3: 表示连接已经关闭
const GetClient = function () {
if (wsClient != null && wsClient.readyState === 1) {
return wsClient
}
NewClient()
return wsClient
}

const NewClient = function () {
wsClient = new WebSocket("ws://localhost:8080/echo");
ws.onopen = function () {
console.log("open");
}
ws.onclose = function (e) {
console.log("close");
reConnect();
}
ws.onerror = function (e) {
console.log(e);
reConnect();
}
return ws
}

const TYPE_NEWPOD = 101;
const NewPod = function (PodName, PodImage, PodNode) {
return {
CmdType: TYPE_NEWPOD,
CmdAction: "add",
CmdData: {
PodName,
PodImage,
PodNode
}
}
}
<template>
<div>
<p>
<el-button @click="testSend">测试发送</el-button>
</p>
<div style="width: 95%;margin: 0 auto">
<div style="width: 95%;margin:30px auto">
<el-table
:data="podList"
border
style="width: 100%">
<el-table-column
prop="PodName"
label="PodName"
width="100">
</el-table-column>
<el-table-column
prop="PodImage"
label="Pod镜像"
width="220">
</el-table-column>
<el-table-column
prop="PodNode"
label="Pod节点"
width="100">
</el-table-column>

</el-table>
</div>

</div>
</div>
</template>
<script type="module">
module.exports = {
data() {
return {
podList: [],
client: null,
}
},
created() {
this.CheckWsClient();
},
methods: {
CheckWsClient() {
this.client = GetClient();
this.client.onmessage = (e) => {
if (e.data !== 'ping') {
console.log(JSON.parse(e.data).Result)
this.$forceUpdate();
}
}
},
testSend() {
// 按钮时间执行的时候也执行一下检测客户端代码
this.CheckWsClient();

// this.client.send("abc");
const pod = NewPod("abc", "aaa", "fe")
this.client.send(JSON.stringify(pod))

const ping = {
CmdType: 999,
CmdAction: "abc",
}
this.client.send(JSON.stringify(ping))
}
}


}
</script>
<style>
.sdt {
margin: 10px auto;
width: 90%;
border-radius: 5px;
display: block;
float: left;
margin-left: 50px
}

.sdt dt {
width: 100%;
display: block;
color: #3A7B43;
font-size: 16px;
font-weight: bold;
margin-bottom: 10px
}

.sdt dd {
float: left;
margin: 0 auto;
text-indent: 1em
}

.sdt .row {
width: 100%;
}

.sdt dd .search {
width: 50%;
}

.sdt dd a {
color: #3a8ee6
}

.sdt dd a:hover {
background: #eb5975;
color: #fff
}

.sdt dd .select {
background: #eb5975;
color: #fff
}

.sdt dd .numtext {
width: 100px
}

.sdt dd span {
margin: 0 auto
}

a {
cursor: pointer
}

.el-pagination {
margin: 0 auto;
float: left
}
</style>