-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
77 lines (70 loc) · 2.26 KB
/
index.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
var app = require('express')();
var cors = require('cors');
var server = require('http').Server(app);
var io = require('socket.io')(server, { origins: '*:*' });
const PORT = process.env.PORT || 3000
app.use(cors())
var room = {};
server.listen(PORT);
// WARNING: app.listen(80) will NOT work here!
console.log(`Web listen on PORT=${PORT}`);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log(socket.id + ' had connected')
console.log(room)
socket.on('message', data => {
data = JSON.parse(data)
if (!room[data.room]) {
room[data.room] = [socket.id]
} else if (room[data.room].length < 2) {
if (room[data.room].filter(i => i === socket.id).length === 0) {
room[data.room].push(socket.id)
}
}
if (room[data.room].length === 2) {
for (s of room[data.room]) {
if (s !== socket.id && io.sockets.sockets[s] && room[data.room].length <= 2) {
io.sockets.sockets[s].emit('message', data.data)
}
}
}
})
socket.on('join', (roomId) => {
console.log('join' + roomId)
if (room[roomId] && room[roomId].length === 2) {
socket.emit('reject', { error: 'Room is full' })
}
})
socket.on('leave', (roomId) => {
console.log('leave' + roomId)
for (s in room) {
for (let i = 0; i < room[s].length; i++) {
if (room[s][i] === roomId) {
room[s].splice(i, 1)
if (room[s].length == 0) {
delete room[s]
}
break
}
}
}
console.log(room)
})
socket.on('disconnect', () => {
console.log(socket.id + ' has been disconnected')
for (s in room) {
for (let i = 0; i < room[s].length; i++) {
if (room[s][i] === socket.id) {
room[s].splice(i, 1)
if (room[s].length == 0) {
delete room[s]
}
break
}
}
}
console.log(room)
})
});