-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
82 lines (70 loc) · 2.71 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
const express = require('express');
const path = require('path')
const favicon = require('serve-favicon');
const ws = require('ws');
const { v4: uuidv4 } = require('uuid');
// Express server
const app = express();
const PORT = process.env.PORT || 8080;
app.use(favicon(path.join(__dirname,'public','favicon.ico')));
app.use(express.static(__dirname+'/build'));
app.get('/*', (req, res, next) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(PORT);
// Websocket server
wss = new ws.Server({port: 40510})
dorms = {1:{}}
wss.on('connection', (socket) => {
const uuid = uuidv4();
socket.send(JSON.stringify({cmd: 'uuid', uuid: uuid}))
const leave = (dormid) => {
if(!dorms[dormid][uuid]) return;
if(Object.keys(dorms[dormid]).length === 1) delete dorms[dormid];
else delete dorms[dormid][uuid];
};
socket.on('message', data => {
const { cmd, dormId, name, status, curUuid } = JSON.parse(data);
if (cmd === 'create') {
// Create new dorm
const newDormId = uuidv4();
dorms[newDormId] = {};
dorms[dormId][uuid] = {};
dorms[dormId][uuid]['socket'] = socket;
dorms[dormId][uuid]['data'] = [name, status];
// Send data back
socket.send(JSON.stringify([[name, status]]))
} else if (cmd === 'join') {
// Check if dorm exists
if (!dorms[dormId]) socket.send('no_room');
// Check if the user exists in the room
else if (dorms[dormId][uuid]) socket.send('already_joined');
else {
// Join room
dorms[dormId][uuid] = {};
dorms[dormId][uuid]['socket'] = socket;
dorms[dormId][uuid]['data'] = [name, status];
}
// Send data about room to uuid
let resData = {}
Object.entries(dorms[dormId]).forEach(([uuid,d]) => {
resData[uuid] = d['data']
});
Object.entries(dorms[dormId]).forEach(([, d]) => {
d['socket'].send(JSON.stringify({ cmd: 'update', data: resData }))
});
socket.send(JSON.stringify({cmd: 'update', data: resData}));
} else if(cmd === 'leave') {
leave(dormId);
} else if(cmd === 'update') {
dorms[dormId][[curUuid]]['data'] = [name, status];
let resData = {}
Object.entries(dorms[dormId]).forEach(([_uuid,d]) => {
resData[_uuid] = d['data']
});
Object.entries(dorms[dormId]).forEach(([, d]) => {
d['socket'].send(JSON.stringify({ cmd: 'update', data: resData }))
});
}
});
});