WebSocket real-time updates: faster polling + network events
- Reduce polling interval to 5 seconds for faster updates - Add network update events (peer count changes) - Include block type (PoS/PoW) in newBlock events - Track connected WebSocket clients - Emit networkUpdate when peer count changes This enables real-time live feed on the explorer frontend.
This commit is contained in:
@@ -352,7 +352,73 @@ app.get('/rest/richlist/status', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(PORT, () => {
|
||||
const server = app.listen(PORT, () => {
|
||||
console.log(`Triangles REST API running on http://localhost:${PORT}`);
|
||||
console.log(`Proxying to Triangles RPC at ${RPC_URL}`);
|
||||
});
|
||||
|
||||
// WebSocket support for real-time updates
|
||||
const { Server } = require('socket.io');
|
||||
const io = new Server(server, {
|
||||
cors: { origin: '*' }
|
||||
});
|
||||
|
||||
let lastBlockHash = null;
|
||||
let connectedClients = 0;
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
connectedClients++;
|
||||
console.log(`WebSocket client connected (${connectedClients} total)`);
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
connectedClients--;
|
||||
console.log(`WebSocket client disconnected (${connectedClients} total)`);
|
||||
});
|
||||
});
|
||||
|
||||
// Poll for new blocks and network stats every 5 seconds
|
||||
let lastNetworkInfo = null;
|
||||
|
||||
async function checkForNewBlocks() {
|
||||
try {
|
||||
const info = await rpc('getinfo');
|
||||
const currentHash = await rpc('getbestblockhash');
|
||||
|
||||
if (lastBlockHash && currentHash !== lastBlockHash) {
|
||||
const block = await rpc('getblock', [currentHash, true]);
|
||||
console.log(`New block detected: ${block.height} (${currentHash.slice(0, 16)}...)`);
|
||||
|
||||
// Get block type
|
||||
const isPoS = block.flags && block.flags.includes('proof-of-stake');
|
||||
|
||||
io.emit('newBlock', {
|
||||
height: block.height,
|
||||
hash: currentHash,
|
||||
time: block.time,
|
||||
tx: block.tx.length,
|
||||
size: block.size,
|
||||
type: isPoS ? 'PoS' : 'PoW',
|
||||
difficulty: block.difficulty
|
||||
});
|
||||
}
|
||||
|
||||
lastBlockHash = currentHash;
|
||||
|
||||
// Network stats updates (only if changed significantly)
|
||||
const currentPeers = info.connections;
|
||||
if (!lastNetworkInfo || Math.abs(currentPeers - lastNetworkInfo.peers) > 0) {
|
||||
io.emit('networkUpdate', {
|
||||
peers: currentPeers,
|
||||
blockHeight: info.blocks,
|
||||
difficulty: info.difficulty
|
||||
});
|
||||
lastNetworkInfo = { peers: currentPeers };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Block polling error:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Start polling (every 5 seconds for faster updates)
|
||||
setInterval(checkForNewBlocks, 5000);
|
||||
checkForNewBlocks(); // Initial check
|
||||
|
||||
Reference in New Issue
Block a user