-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
112 lines (91 loc) · 2.81 KB
/
server.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
const Socket = require("websocket").server
const http = require("http")
const server = http.createServer((req, res) => {})
server.listen(3000, () => {
console.log("Listening on port 3000...")
})
const webSocket = new Socket({ httpServer: server })
let users = []
webSocket.on('request', (req) => {
const connection = req.accept()
connection.on('message', (message) => {
const data = JSON.parse(message.utf8Data)
const user = findUser(data.username)
switch(data.type) {
case "store_user":
if (user != null) {
return;
}
const newUser = {
conn: connection,
username: data.username
}
users.push(newUser)
console.log(newUser.username)
break
case "store_offer":
if (user == null)
return
user.offer = data.offer
break
case "store_candidate":
if (user == null) {
return
}
if (user.candidates == null)
user.candidates = []
user.candidates.push(data.candidate)
break
case "send_answer":
if (user == null) {
return
}
sendData({
type: "answer",
answer: data.answer
}, user.conn)
break
case "send_candidate":
if (user == null) {
return
}
sendData({
type: "candidate",
candidate: data.candidate
}, user.conn)
break
case "join_call":
if (user == null) {
return
}
sendData({
type: "offer",
offer: user.offer
}, connection)
user.candidates.forEach(candidate => {
sendData({
type: "candidate",
candidate: candidate
}, connection)
})
break
}
})
connection.on('close', (reason, description) => {
users.forEach(user => {
if (user.conn == connection) {
users.splice(users.indexOf(user), 1)
return
}
})
})
})
function sendData(data, conn) {
conn.send(JSON.stringify(data))
}
function findUser(username) {
for (let i = 0;i < users.length;i++) {
if (users[i].username == username)
return users[i]
}
}