This repository has been archived on 2025-07-16. You can view files and clone it, but cannot push or open issues or pull requests.
Files
vue-with-websockets/backend/index.js
2025-07-07 19:14:06 +03:00

41 lines
1.4 KiB
JavaScript

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);