-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (83 loc) · 2.59 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//required node packages
const express = require("express");
const socket = require('socket.io')
const app = express();
const port = process.env.PORT || 3000;
const path = require("path");
const bodyParser = require("body-parser");
let rooms = [{ rid: 'fake', uid: 'fake' }];
//using bodyParser, ejs view engine and static page
app.use(bodyParser.json());
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "./templates")));
const server = require('http').createServer(app);
const io = socket(server);
server.listen(port, () => {
console.log(`Server started in port ${port}`);
});
//----------------------------------------------------------------------------------//
//Basic page routings
app.get('/', (req, res) => {
res.render('index');
})
app.get('/track', (req, res) => {
res.render('track');
})
app.get('/betrack', (req, res) => {
res.render('betrack');
})
//-------------------------------------------------------------------------//
//socket.io on connection activity
io.on('connection', (socket) => {
console.log('connection stablished');
//connection from client-betracked ans storing roomid/hostid
socket.on('beconn', (code) => {
socket.join(code);
let rid = code;
let uid = socket.id;
rooms.push({ rid, uid });
console.log(`${code} romm joined`);
console.log(rooms)
})
//connection from client-track and checking entered roomid
socket.on('tconn', (code) => {
if (rooms.find(e => e.rid == code)) {
socket.join(code);
io.emit('check', 'true');
console.log(rooms)
console.log(`${code} room joined`);
}
else {
io.emit('check', 'false');
console.log('invalif room id');
}
})
//sending location coordinates to client-track and vice versa
socket.on('getCo', (lat) => {
io.in(lat.codeg).emit('co', lat);
console.log(lat);
})
//socket disconnect from client-(betracked/track)
//remove roomid/hostid on disconnect from client-betrack
socket.on('discon', (msg) => {
if (rooms.find(e => e.uid == socket.id)) {
rooms = rooms.filter(id => id.rid != msg);
io.in(msg).emit('belast', 'Last Known Location');
io.socketsLeave(msg);
}
else {
socket.leave(msg);
}
})
//socket on automatic disconnect
//remove roomid/hostid if client-betracked
socket.on('disconnect', () => {
let luser = rooms.find(e => e.uid == socket.id);
if (luser) {
io.in(luser.rid).emit('belast', 'Last Known Location');
io.socketsLeave(luser.rid);
rooms = rooms.filter(id => id.uid != socket.id);
}
})
})
//###########-------EOF-------###########\\