<template>
<div></div>
</template>
<script>
export default {
data() {
return {
websock: null,
lockReconnect: false,
timeout: 20 * 1000,
timeoutObj: null,
serverTimeoutObj: null,
timeoutnum: null,
}
},
created() {
this.initWebSocket()
},
destroyed() {
this.websocketclose()
},
methods: {
initWebSocket() {
const wsuri = 'ws://localhost:9998/echo'
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
},
websocketonopen() {
this.websocketsend('发送数据')
console.log('连接成功', 3)
this.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)
},
websocketonmessage(event) {
console.log('收到服务器信息', event.data)
let data = event.data
this.reset()
},
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()
},
websocketonerror(e) {
console.log('WebSocket连接发生错误')
this.reconnect()
},
websocketclose(e) {
console.log('连接已关闭')
this.reconnect()
},
websocketsend(msg) {
this.websock.send(msg)
},
},
}
</script>
<style scoped></style>
blog.51cto.com/u_13206321/…