-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
62 lines (50 loc) · 1.81 KB
/
Copy pathscript.js
File metadata and controls
62 lines (50 loc) · 1.81 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
import express from "express";
const app = express();
import http from "http";
import path from "path";
import { fileURLToPath } from "url";
import { Server } from "socket.io";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const server =http.createServer(app);
const io = new Server(server);
let userCount = 0;
const connectedUsers = new Map();
io.on("connection",(socket)=>{
userCount++;
const isFirstUser = userCount === 1;
console.log(`User ${socket.id} connected. Total: ${userCount}, First: ${isFirstUser}`);
// When a new user connects, send all existing user locations to them
connectedUsers.forEach((location, userId) => {
socket.emit("receiveLocation", {id: userId, ...location});
});
socket.on("checkFirstUser", () => {
console.log(`Sent user status to ${socket.id}: First=${isFirstUser}`);
});
socket.on("sendLocation",function(data){
const isFirstLocation = !connectedUsers.has(socket.id);
connectedUsers.set(socket.id, data);
io.emit("receiveLocation",{id:socket.id, ...data});
if (isFirstLocation) {
connectedUsers.forEach((location, userId) => {
if (userId !== socket.id) {
socket.emit("receiveLocation", {id: userId, ...location});
}
});
}
});
socket.on("disconnect",()=>{
userCount--;
connectedUsers.delete(socket.id);
console.log(`User ${socket.id} disconnected. Total: ${userCount}`);
io.emit("userDisconnected",socket.id);
})
})
app.set("view engine","ejs");
app.use(express.static(path.join(__dirname,"public")));
app.get("/",(req,res)=>{
res.render("index")
})
server.listen(3000,()=>{
console.log("Server is running on port 3000")
})