import { WebSocketServer } from 'ws'; import HistoryFile from './classes/HistoryFile.js'; import { MIN, MAX, RANGE } from './consts.js'; import { randomInt, randomInRange } from './utils/random.js'; // Define History file class // For managing data state beyond restart const history = new HistoryFile('data.json'); // Define WebSocket server const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', (ws) => { // On successful connection, we send history data to the client // After that, we procceed sending data update every 10 seconds ws.send(JSON.stringify({ type: 'history', data: history.history })); }); // Generate initial random number, or take it from the history if that exists let previousNumber = randomInt(MIN, MAX); if (history.history.length > 0) { previousNumber = history.history[history.history.length - 1].number; } /* * Execute every 10 seconds * This will update hisotry data, by appending new entry * Then save this data to a history file * And notify all clients about new data entry */ setInterval(() => { const newNumber = randomInRange(previousNumber, RANGE, MIN, MAX); const newEntry = history.append(newNumber); // Send new entry to all connected clients wss.clients.forEach((client) => { if (client.readyState !== WebSocket.OPEN) return; client.send(JSON.stringify({ type: 'update', data: newEntry })); }); }, 10 * 1000);