ipc: clean and use same method to check connection state on both sides

This commit is contained in:
jean-emmanuel 2018-02-09 10:56:01 +01:00
parent fad164ed48
commit b2ba508854
3 changed files with 25 additions and 27 deletions

View file

@ -12,7 +12,6 @@ class Ipc extends EventEmitter {
super()
this.socket = null
this.connected = false
this.queue = []
@ -44,37 +43,18 @@ class Ipc extends EventEmitter {
}
close() {
this.socket = null
this.connected = false
this.hearbeat = clearInterval(this.hearbeat)
this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
if (!this.reconnect) {
this.reconnect = setInterval(()=>{
this.open()
}, reconnectInterval)
}
}
open() {
this.socket = new WebSocket('ws://' + window.location.host + '/' + uuid)
this.socket.onopen = (e)=>{
this.connected = true
this.reconnect = clearInterval(this.reconnect)
this.hearbeat = setInterval(()=>{
this.socket.send(`["ping"]`)
this.hearbeatTimeout = setTimeout(()=>{
this.socket.close()
if (this.connected()) this.socket.close()
}, hearbeatTimeout)
}, hearbeatInterval)
@ -87,16 +67,33 @@ class Ipc extends EventEmitter {
this.receive(e.data)
}
this.socket.onclose = (e)=>{
this.socket.onclose = this.socket.onerror = ()=>{
this.close()
}
this.socket.onerror = (e)=>{
this.close()
}
close() {
this.socket = null
this.hearbeat = clearInterval(this.hearbeat)
this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
if (!this.reconnect) {
this.reconnect = setInterval(()=>{
this.open()
}, reconnectInterval)
}
}
connected() {
return this.socket.readyState == this.socket.OPEN
}
receive(message) {
if (typeof message == 'string') {
@ -117,7 +114,7 @@ class Ipc extends EventEmitter {
var packet = JSON.stringify([event, data])
if (this.connected) {
if (this.connected()) {
this.socket.send(packet)
} else {
this.queue.push(packet)