export default class WebSocketClient {
constructor () {
this.ws = null // websocket实例
this.connecting = false // 正在连接
this.reconnectSettimeout = null // 重新连接的setTimeout
this.timeout = 3000 // 心跳监测间隔
this.timeoutObj = null
this.serverTimeoutObj = null
this.handleMessage = {}
this.createWebSocket()
}
createWebSocket () {
try {
this.ws = new WebSocket(process.env.WEBSOCKET_URL)
this.handlerMessage()
} catch (error) {
console.log('catch')
this.reconnect()
}
}
reconnect () {
if (this.connecting) return
this.connecting = true
this.reconnectSettimeout && clearTimeout(this.reconnectSettimeout)
this.reconnectSettimeout = setTimeout(() => {
this.createWebSocket()
this.connecting = false
}, 4000)
}
startHeartcheck () {
this.timeoutObj && clearTimeout(this.timeoutObj)
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
this.timeoutObj = setTimeout(() => {
this.ws.send('ping')
this.serverTimeoutObj = setTimeout(() => {
this.ws.close()
}, this.timeout)
}, this.timeout)
}
handlerMessage () {
const that = this
that.ws.onopen = function () {
console.log('ws has opened')
this.startHeartcheck()
}
that.ws.onmessage = function (e) {
try {
this.startHeartcheck()
const data = JSON.parse(e.data)
if (data.message && that.handleMessage[data.message]) {
that.handleMessage[data.message](data)
}
} catch (e) {
console.warn(e)
}
}
that.ws.onclose = function (restart) {
console.log('ws closed')
restart && this.reconnect()
}
that.ws.onerror = function () {
console.log('ws erred')
this.reconnect()
}
}
registerHandler (msg, handle) {
const that = this
const handler = {}
handler[msg] = handle
Object.assign(that.handleMessage, handler)
}
cancelRegister (msg) {
if (msg) {
delete this.handleMessage[msg]
}
}
sendMsg (msg) {
this.ws && this.ws.send(JSON.stringify(msg))
}
close (restart) {
this.ws.close(restart)
}
}
网友评论