-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
87 lines (74 loc) · 2.17 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
const http = require("http");
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');
const PATH_MAP = {
"/": {
path: "index.html",
contentType: "text/html"
},
"/app.js": {
path: "app.js",
contentType: "text/javascript"
}
};
const server = http.createServer((req, res) => {
let requestPath = req.url;
const queryParamIndex = requestPath.indexOf("?");
if (queryParamIndex > 0) {
requestPath = requestPath.substring(0, queryParamIndex);
}
const pathMapping = PATH_MAP[requestPath];
if (pathMapping) {
res.statusCode = 200;
res.setHeader("Content-Type", pathMapping.contentType);
const payload = fs.readFileSync(path.join(__dirname, pathMapping.path));
res.end(payload);
} else {
res.statusCode = 404;
res.end();
}
});
const wss = new WebSocket.Server({server});
let socketIdCount = 1;
const clients = {};
let hostId;
wss.on('connection', (ws) => {
ws.id = socketIdCount++;
clients[ws.id] = ws;
ws.on('message', (message) => {
const data = JSON.parse(message);
if (data.type === 'HostRequest') {
if (!hostId) {
hostId = ws.id;
ws.send(JSON.stringify({
type: 'HostResponse',
success: true
}));
} else {
ws.send(JSON.stringify({
type: 'HostResponse',
success: false
}));
}
} else if (data.type === 'RTCOffer') {
const target = clients[data.targetId];
target.send(JSON.stringify(data.offer));
} else if (data.type === 'answer') {
clients[hostId].send(JSON.stringify({
type: 'answer',
answer: data,
targetId: ws.id
}));
} else if (data.type === 'PeerRequest') {
clients[hostId].send(JSON.stringify({
type: "PeerRequest",
id: ws.id
}));
}
});
ws.on('close', () => {
delete clients[ws.id];
});
});
server.listen(80);