-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
52 lines (42 loc) · 1.56 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
const http = require('http');
const express = require('express');
const socketio = require('socket.io')
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// const rooms={}
let roomAcceptingEntry = false;
const playerLimit = 5;
app.use(express.static(__dirname));
io.on('connection', socket => {
console.log('a user connected with id = ' + socket.id)
socket.on("scoreUpdate", score => socket.broadcast
.to(roomOf(socket))
.emit(
'scoreUpdateToClient', socket.id,score
))
addToRandomRoom()
async function addToRandomRoom() {
usersInRoom(roomAcceptingEntry).then(numberOfUsers => {
console.log("users in this room: ", numberOfUsers)
if (numberOfUsers < playerLimit) {
socket.join(roomAcceptingEntry);
} else {
socket.join(socket.id);
roomAcceptingEntry = socket.id;
}
socket.broadcast.to(roomOf(socket)).emit('userJoined', socket.id)
}).catch(e => console.log(e))
}
})
const PORT = process.env.PORT || 3000
server.listen(PORT, () => { console.log(`Server running on port ${PORT}`) })
function roomOf(socket) {
let roomArray = Array.from(socket.rooms);
//we assume socket has joined 2 rooms only ;one it's default room (id) and other in which game gonna happen
return roomArray[0] = socket.id ? roomArray[1] : roomArray[0];
}
async function usersInRoom(room) {
let setOfIdsInRoom = await io.in(room).allSockets();
return setOfIdsInRoom.size;
}