-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
130 lines (103 loc) · 3.3 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// const Socket = require("websocket").server
// const http = require("https")
// const port = process.env.PORT || 8000
const PORT = process.env.PORT || 3000;
const INDEX = '/sender.html';
const server = express()
.use((req, res) => res.sendFile(INDEX, { root: __dirname }))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
// const server = http.createServer((req, res) => {})
// server.listen(port, () => {
// console.log(`Listening on port ${port}`)
// })
const webSocket = new Socket({ httpServer: server })
// const { Server } = require('ws');
// const wss = new Server({ server });
// wss.on('connection', (ws) => {
// console.log('Client connected');
// ws.on('close', () => console.log('Client disconnected'));
// });
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]
}
}