forked from cerebral/overmind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionManager.js
More file actions
65 lines (57 loc) · 1.71 KB
/
ConnectionManager.js
File metadata and controls
65 lines (57 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const WebSocketServer = require('ws').Server
class ConnectionManager {
constructor(mainWindow) {
this.mainWindow = mainWindow
this.clients = {}
this.onDevtoolsMessage = this.onDevtoolsMessage.bind(this)
this.onAddPort = this.onAddPort.bind(this)
this.onRemovePort = this.onRemovePort.bind(this)
}
addClient(port, client) {
const onConnection = this.onConnection.bind(this, port)
const onError = this.onError.bind(this, port)
this.clients[port] = {
wss: client,
dispose() {
client.removeListener('connection', onConnection)
client.removeListener('error', onError)
client.close()
},
}
this.clients[port].wss.on('connection', onConnection)
this.clients[port].wss.on('error', onError)
this.mainWindow.webContents.send('port:added', port)
}
onError(port) {
this.mainWindow.webContents.send('port:exists', port)
}
onConnection(port, ws) {
this.clients[port].ws = ws
ws.on('message', this.onAppMessage.bind(this, port))
}
onAppMessage(port, message) {
const parsedMessage = JSON.parse(message)
this.mainWindow.webContents.send('message', {
port,
message: parsedMessage,
})
}
onDevtoolsMessage(_, payload) {
if (!this.clients[payload.port] || !this.clients[payload.port].ws) {
return
}
this.clients[payload.port].ws.send(JSON.stringify(payload))
}
onAddPort(_, port) {
if (this.clients[port]) {
this.mainWindow.webContents.send('port:added', port)
return
}
this.addClient(port, new WebSocketServer({ port: Number(port) }))
}
onRemovePort(_, port) {
this.clients[port].dispose()
delete this.clients[port]
}
}
module.exports = ConnectionManager