-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
63 lines (50 loc) · 1.93 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
const { WebSocketServer } = require('ws');
const http = require('http');
const server = http.createServer();
const wss = new WebSocketServer({ server });
let messageLog = []; // Array to store all messages
// Function to calculate the time remaining until the next midnight
function getMillisecondsUntilMidnight() {
const now = new Date();
const midnight = new Date(now);
midnight.setHours(24, 0, 0, 0); // Set to midnight (00:00:00.000)
return midnight - now; // Time remaining until midnight in milliseconds
}
// Function to clear the log at midnight
function clearLogAtMidnight() {
// Clear the log
console.log('Clearing message log at midnight...');
messageLog = [];
// Calculate the time until the next midnight and set a timeout to call this function again
const timeUntilNextMidnight = getMillisecondsUntilMidnight();
setTimeout(clearLogAtMidnight, timeUntilNextMidnight);
}
// Start the first clearing at the next midnight
const initialTimeUntilMidnight = getMillisecondsUntilMidnight();
setTimeout(clearLogAtMidnight, initialTimeUntilMidnight);
wss.on('connection', (ws) => {
console.log('Client connected');
// When a message is received from a client
ws.on('message', (message) => {
message = message.toString();
console.log('Received:', message);
// Save the message to the messageLog array
messageLog.push(message);
// Broadcast the updated log to all connected clients
const logMessage = '(LOG)' + JSON.stringify({ logs: messageLog });
wss.clients.forEach(client => {
if (client.readyState === ws.OPEN) {
client.send(logMessage);
}
});
// Send a confirmation back to the sender
ws.send('Message received and logged');
});
// When the connection is closed
ws.on('close', () => {
console.log('Client disconnected');
});
});
server.listen(process.env.PORT || 8000, () => {
console.log(`WebSocket server running on port ${process.env.PORT || 8000}`);
});