-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
49 lines (42 loc) · 1.52 KB
/
app.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
// Import required modules
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
// Create Express app
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// Serve the main HTML file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Socket.io logic
io.on('connection', (socket) => {
console.log('A user connected');
// Listen for button press event
socket.on('buttonPress', () => {
// Generate a random number between 1 and 6
const randomNumber1 = Math.floor(Math.random() * 6) + 1;
// Emit the random number to all connected clients
io.emit('randomNumber', randomNumber1);
const randomNumber2 = Math.floor(Math.random() * 6)+ 1;
// Emit the random number to all connected clients
io.emit('randomNumber', randomNumber2);
// Generate a random number between 1 and 100
const sumOfNumber = randomNumber1 + randomNumber2;
// Emit the random number to all connected clients
io.emit('sumOfNumbers', sumOfNumber );
});
// Handle disconnection
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});