This repository has been archived by the owner on May 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclientSocketMapper.js
54 lines (47 loc) · 1.83 KB
/
clientSocketMapper.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
const userSocketIdMap = new Map(); //a map of online usernames and their clients
module.exports = {
addClientToMap: function (userName, socketId, gameId){
if (!userSocketIdMap.has(userName)) {
//when user is joining first time
userSocketIdMap.set(userName, { sockets: new Set([socketId]), games: new Set([gameId])});
} else {
//user had already joined from one client and now joining using another client
userSocketIdMap.get(userName).sockets.add(socketId);
userSocketIdMap.get(userName).games.add(gameId);
}
},
removeClientFromMap: function (userName, socketId, gameId){
if (userSocketIdMap.has(userName)) {
let userSocketIdSet = userSocketIdMap.get(userName);
userSocketIdSet.sockets.delete(socketId);
userSocketIdSet.games.delete(gameId);
//if there are no clients for a user, remove that user from online list (map)
if (userSocketIdSet.size == 0 ) {
userSocketIdMap.delete(userName);
}
}
},
getClientNameFromMap: function (socketId) {
var name = null;
userSocketIdMap.forEach(function(value, key) {
// console.log(value);
const sockets = Array.from(value.sockets);
for (var i = 0; i < sockets.length; i++) {
// console.log(sockets[i]);
if (sockets[i] == socketId) {
name = key;
}
}
});
return name;
},
getSocketsFromMap: function (userName) {
if (userSocketIdMap.has(userName)) {
return userSocketIdMap.get(userName).sockets;
}
},
isUserConnected: function (userName) {
return userSocketIdMap.has(userName);
},
userSocketIdMap: userSocketIdMap,
}