-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (46 loc) · 1.17 KB
/
index.js
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
const io = require("socket.io")()
const shortid = require("shortid")
const modules = {}
function mobileSocket(socket) {
console.log("<- mobile")
socket.join("mobiles")
Object.keys(modules).forEach(id => {
socket.emit("module", {id, type: modules[id].type})
})
socket.on("dispatch", data => {
modules[data.id].socket.emit(data.action, data.payload)
})
}
function moduleSocket(module) {
const {socket, id} = module
socket.on("dispatch", data => {
console.log(`<- dispatch: ${JSON.stringify({...data, id})}`)
io.to("mobiles").emit("dispatch", {
...data,
id,
})
})
socket.on("disconnect", () => {
io.to("mobiles").emit("leave", id)
delete modules[id]
})
}
io.on("connection", socket => {
console.log("<- connection")
socket.on("type", type => {
if (type === "MOBILE") mobileSocket(socket)
else {
const id = shortid.generate()
const module = {
id,
socket,
type,
}
console.log(`<- type: {id: ${id}, type: ${type}}`)
modules[id] = module
io.to("mobiles").emit("module", {id, type})
moduleSocket(module)
}
})
})
io.listen(process.env.PORT || 3000)