-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
93 lines (76 loc) · 2.08 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
const express = require('express');
const bodyParser = require('body-parser');
const randomstring = require('randomstring');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
let clients = {};
let rooms = {};
app.use(express.static('dist'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
io.on('connection', (socket) => {
function log(data) {
socket.broadcast.emit('message', data);
}
socket.on('createRoom', () => {
let room = randomstring.generate({
length: 5,
charset: 'alphanumeric',
capitalization: 'lowercase'
});
socket.join(room);
clients[socket] = room;
rooms[room] = 1;
socket.emit('room', room);
});
socket.on('joinRoom', (room) => {
socket.join(room);
clients[socket] = room;
rooms[room]++;
});
socket.on('handshake', (data, room) => {
socket.broadcast.in(room).emit('handshake', data);
});
socket.on('exit', (room) => {
socket.broadcast.in(room).emit('exit');
delete rooms[room];
});
});
function generateCode() {
let code = randomstring.generate({
length: 5,
charset: 'alphanumeric',
capitalization: 'lowercase'
});
while(code in rooms) {
code = randomstring.generate({
length: 5,
charset: 'alphanumeric',
capitalization: 'lowercase'
});
}
return code;
}
app.post('/checkVacancy', (req, res) => {
if (req.body.room in rooms) {
if (rooms[req.body.room] < 2) {
res.json({
vacancy: true
});
} else {
res.json({
vacancy: false,
msg: `Sorry, this room is full.`
})
}
} else {
res.json({
vacancy: false,
msg: `This room doesn't exist. Plese check your code.`
})
}
});
server.listen(3333, () => {
console.log(`Server started on port 3333`);
})