webSocket () {
const that = this
if (window.WebSocket) {
let locationOrigin = window.location.origin.replace('http://', '')
let header = 'ws://'
if (window.location.origin.startsWith('https')) {
header = 'wss://'
locationOrigin = window.location.origin.replace('https://', '')
}
that.ws = new WebSocket(header + locationOrigin + '/websocket' + '?' + sessionStorage.getItem('userCode') +
',;' + sessionStorage.getItem('token') + ',;' + sessionStorage.getItem('authToken') + ',;' + '1')
that.ws.onopen = function () {
that.start()
that.ws.send(
JSON.stringify({
userCode: sessionStorage.getItem('userCode')
})
)
}
that.ws.onmessage = function (msg) {
console.log('接收message', msg.data)
}
that.ws.onerror = that.websocketerror()
that.ws.onclose = that.websocketclose()
}
},
websocketerror () {
this.reconnect()
},
websocketclose () {
let that = this
clearInterval(that.timeIntervalObj)
clearTimeout(that.serverTimeoutObj)
},
start () {
let self = this
self.timeIntervalObj && clearInterval(self.timeIntervalObj)
self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
self.timeIntervalObj = setInterval(function () {
if (self.ws.readyState === 1) {
self.ws.send('heartCheck')
} else {
self.reconnect()
}
}, self.timeout)
},
reset () {
let that = this
clearInterval(that.timeIntervalObj)
clearTimeout(that.serverTimeoutObj)
that.start()
},
reconnect () {
let that = this
if (that.lockReconnect) {
return
}
that.lockReconnect = true
that.timeoutnum && clearTimeout(that.timeoutnum)
that.timeoutnum = setTimeout(function () {
that.webSocket()
that.lockReconnect = false
}, 5000)
},
ws: null,
webSocketPath: 'localhost:13222',
lockReconnect: false,
timeout: 8 * 1000,
timeIntervalObj: null,
serverTimeoutObj: null,
timeoutnum: null,