feat(ws): send history data and update data with web socket
Added following logic: 1. New clients receive 15 entry history from history file 2. After that, every 10 seconds when new entry is generated it is sent out to all connected clients
This commit is contained in:
@@ -1,26 +1,41 @@
|
||||
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 WebSocket server
|
||||
const wss = new WebSocketServer({ port: 8080 });
|
||||
// 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
|
||||
console.log('Client connected');
|
||||
|
||||
ws.on('message', (message) => {
|
||||
console.log(`Received message => ${message}`);
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
console.log('Client disconnected');
|
||||
});
|
||||
|
||||
ws.send('Hello! Message from server.');
|
||||
ws.send(JSON.stringify({ type: 'history', data: history.history }));
|
||||
});
|
||||
|
||||
console.log('WebSocket server is running on ws://localhost:8080');
|
||||
// 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;
|
||||
console.log(`Previous number: ${previousNumber}`);
|
||||
}
|
||||
|
||||
/*
|
||||
* 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);
|
||||
|
||||
Reference in New Issue
Block a user