-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
116 lines (101 loc) · 2.59 KB
/
app.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const uuidv1 = require('uuid/v1')
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 })
const log = console.log
// Use DB?
var lobbies = []
var peers = []
var methods = {
addLobby(message, ws){
log("addLobby")
lobbies.push(JSON.parse(message.lobby))
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
method: 'lobbyAdded',
lobby: message.lobby,
}))
}
})
},
joinLobby(message, ws){
let lobby = lobbies.find(lobby => lobby.id == message.lobby_id)
lobby.peers.push(message.peer)
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
method: 'peerJoined',
peer: message.peer,
lobby: lobby,
}))
}
})
},
peerBAnswer(message, ws){
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
method: 'peerBAnswer',
to: message.to,
from: message.from,
desc: message.desc
}))
}
})
},
peerCandidate(message, ws){
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
method: 'peerCandidate',
to: message.to,
from: message.from,
candidate: message.candidate,
}))
}
})
},
closeLobbies(message, ws){
lobbies = []
syncLobbies(ws)
},
updateLobby(message, ws){
lobbies.forEach(lobby => {
if(lobby.id == message.lobby.id){
lobby = message.lobby
}
})
},
syncLobbies(ws){
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
method: 'lobbiesUpdated',
lobbies: lobbies
}))
}
})
},
syncLobby(ws, lobby){
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
method: 'lobbyUpdated',
lobby: lobby
}))
}
})
}
}
wss.on('connection', function connection(ws) {
lobbies = []
ws.on('message', function incoming(message) {
message = JSON.parse(message)
methods[message.method](message, ws)
})
// Init
ws.send(JSON.stringify({
method: 'init',
lobbies: lobbies
}))
})