-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
63 lines (53 loc) · 1.87 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
53
54
55
56
57
58
59
60
61
62
63
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const { v4: uuidv4 } = require('uuid');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
let timers = {};
// Serve static files from 'public' directory
app.use(express.static('public'));
// Endpoint to create a new timer
app.get('/create-timer', (req, res) => {
const timerId = uuidv4(); // Generate unique timer ID
timers[timerId] = { time: 0, running: false }; // Initialize timer state
res.json({ timerId });
});
io.on('connection', (socket) => {
console.log('A user connected');
// User joins a timer room
socket.on('joinTimer', (timerId) => {
socket.join(timerId);
socket.emit('timerUpdate', timers[timerId]); // Send current timer state to new user
// Start the timer
socket.on('startTimer', () => {
if (timers[timerId] && !timers[timerId].running) {
timers[timerId].running = true;
io.to(timerId).emit('timerStarted'); // Notify all users in the room
console.log(`Timer ${timerId} started`); // Debug log
}
});
// Stop the timer
socket.on('stopTimer', () => {
if (timers[timerId] && timers[timerId].running) {
timers[timerId].running = false;
io.to(timerId).emit('timerStopped'); // Notify all users in the room
console.log(`Timer ${timerId} stopped`); // Debug log
}
});
});
});
// Update timers every second
setInterval(() => {
for (const [id, timer] of Object.entries(timers)) {
if (timer.running) {
timer.time += 1; // Increment time
io.to(id).emit('timerUpdate', timer); // Broadcast updated time to users in this room
console.log(`Timer ${id} updated to ${timer.time}`); // Debug log
}
}
}, 1000);
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});