<script>
data() {
// 心跳--start
heartCheck: null,
lockReconnect: false, //避免ws重连
ws: null,
wsUrl: null,
// 心跳--end
},
mounted() {
_this.heartCheck = {
timeout: 1000, //1分钟发一次心跳
timeoutObj: null,
serverTimeoutObj: null,
reset: function () {
clearTimeout(this.timeoutObj)
clearTimeout(this.serverTimeoutObj)
return this
},
start: function () {
var self = this
this.timeoutObj = setTimeout(() => {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
_this.ws.send('ping')
// console.log("ping")
self.serverTimeoutObj = setTimeout(() => {
//如果超过一定时间还没重置,说明后端主动断开了
_this.ws.close() //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
},
}
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket
}
if (window.WebSocket) {
_this.wsUrl = 'ws://192.168.3.54:6002/ws?projectSonId=' + localStorage.getItem('edrId')
_this.ws = new WebSocket(_this.wsUrl) //接口地址
_this.createWebSocket(_this.ws, _this.wsUrl)
} else {
alert('您的浏览器不支持WebSocket协议!')
}
},
methods:{
// 创建ws
createWebSocket(ws, url) {
try {
this.initEventHandle(ws, url)
} catch (e) {
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket
}
if (window.WebSocket) {
_this.wsUrl = 'ws://122.14.196.211:8899/ws?projectSonId=' + localStorage.getItem('edrId')
_this.ws = new WebSocket(_this.wsUrl) //接口地址
_this.createWebSocket(_this.ws, _this.wsUrl)
} else {
alert('您的浏览器不支持WebSocket协议!')
}
}
},
// 监听
initEventHandle(ws, wsUrl) {
let _this = this
ws.onclose = function () {
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket
}
if (window.WebSocket) {
_this.wsUrl = 'ws://122.14.196.211:8899/ws?projectSonId=' + localStorage.getItem('edrId')
_this.ws = new WebSocket(_this.wsUrl) //接口地址
_this.createWebSocket(_this.ws, _this.wsUrl)
} else {
alert('您的浏览器不支持WebSocket协议!')
}
console.log('llws连接关闭!' + new Date().toLocaleString())
}
ws.onerror = function () {
console.log('llws连接错误!')
}
ws.onmessage = function (event) {
//如果获取到消息,心跳检测重置
_this.heartCheck.reset().start() //拿到任何消息都说明当前连接是正常的
console.log('llws收到消息啦:' + event.data)
// console.log(event.data)
console.log(event.data)
}
ws.onopen = function () {
_this.heartCheck.reset().start() //心跳检测重置
console.log('llws连接成功!')
}
},
}
<script/>