ipc: remove socket.io, rewrite ultra slim ipc

This commit is contained in:
jean-emmanuel 2018-02-08 23:21:02 +01:00
parent 874d6f04f9
commit 73bc2e4187
11 changed files with 317 additions and 41 deletions

View file

@ -1,25 +1,33 @@
var io = require('socket.io-client/dist/socket.io.slim.js')
var EventEmitter = require('wolfy87-eventemitter'),
uuid = require('shortid').generate()
var reconnectInterval = 5000,
hearbeatInterval = 25000,
hearbeatTimeout = 5000
var Ipc = class Ipc {
class Ipc extends EventEmitter {
constructor() {
constructor() {
this.socket = io.connect('/')
super()
}
this.socket = null
this.connected = false
this.queue = []
send(event, data) {
this.reconnect = undefined
this.socket.compress(false).emit(event, data)
this.hearbeat = undefined
this.hearbeatTimeout = undefined
this.on('pong', ()=>{
this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
})
this.on('ping', ()=>{
this.socket.send(`["pong"]`)
})
}
on(name, fn) {
this.socket.on(name, fn)
this.open()
}
@ -35,8 +43,101 @@ var Ipc = class Ipc {
}
}
}
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()
}, hearbeatTimeout)
}, hearbeatInterval)
this.trigger('connect')
this.flush()
}
this.socket.onmessage = (e)=>{
this.receive(e.data)
}
this.socket.onclose = (e)=>{
this.close()
}
this.socket.onerror = (e)=>{
this.close()
}
}
receive(message) {
if (typeof message == 'string') {
var packet = JSON.parse(message);
if (Array.isArray(packet) && typeof packet[0] == "string") {
this.emit(packet[0], packet[1])
}
}
}
send(event, data) {
var packet = JSON.stringify([event, data])
if (this.connected) {
this.socket.send(packet)
} else {
this.queue.push(packet)
}
}
flush(){
for (var i in this.queue) {
this.socket.send(this.queue[i])
}
this.queue = []
}
}
var ipc = new Ipc()

View file

@ -19,9 +19,9 @@ var WidgetManager = class WidgetManager extends EventEmitter {
this.on('change', this.onChange, this)
ipc.on('reconnect', ()=>{
ipc.on('connect', ()=>{
for (var hash in this.widgets) {
this.registerWidget(this.widget[hash])
this.registerWidget(this.widgets[hash])
}
})