-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocketRouting.js
More file actions
63 lines (55 loc) · 2 KB
/
socketRouting.js
File metadata and controls
63 lines (55 loc) · 2 KB
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
const {wsAuth} = require("./auth.js");
const {leaveTable} = require("./controllers/manageTables.js");
const userController = require("./controllers/user.js");
const location = require("./controllers/location.js");
const closeExtraConnection = (clients, newClient, userId, location)=>{
let exists = false;
clients.forEach((client)=>{
if(client.user === userId){
newClient.send(JSON.stringify({action: "status"}));
newClient.close(3001);
exists = true;
}
});
if(!exists){
newClient.user = userId;
newClient.location = location
}
}
module.exports = (wss)=>{
wss.on("connection", (client)=>{
client.on("message", (message)=>{
let data = JSON.parse(message);
wsAuth(data.token)
.then((user)=>{
if(!user) throw "auth";
switch(data.action){
case "status": closeExtraConnection(wss.clients, client, user._id.toString(), data.location); break;
case "getLocation": location.getLocation(data.location, client, user); break;
case "participantLeft": leaveTable(data.location, user._id.toString()); break;
case "updateIcon": userController.updateIcon(user, data.location, wss.clients); break;
}
})
.catch((err)=>{
console.error(err);
});
});
client.on("close", (code)=>{
if(code === 3001) return;
leaveTable(client.location, client.user);
});
client.on("pong", ()=>{
client.isAlive = true;
})
});
const ping = setInterval(()=>{
wss.clients.forEach((client)=>{
if(client.isAlive === false){
client.terminate();
leaveTable(client.location, client.user);
}
client.isAlive = false;
client.ping();
});
}, 30000);
}