54 lines
1.5 KiB
JavaScript
54 lines
1.5 KiB
JavaScript
const http = require('http');
|
|
const express = require('express');
|
|
const { createClient } = require('redis');
|
|
const { Server } = require('socket.io');
|
|
|
|
const app = express();
|
|
const server = http.createServer(app);
|
|
const io = new Server(server);
|
|
|
|
// Serve static files (index.html)
|
|
app.use(express.static('public'));
|
|
|
|
// ---------- Redis subscriber ----------
|
|
const redisClient = createClient({
|
|
url: 'redis://172.17.0.1:6379'
|
|
});
|
|
redisClient.on('error', err => console.error('Redis error', err));
|
|
|
|
(async () => {
|
|
await redisClient.connect();
|
|
|
|
// Subscribe to the channel that sends disk lists
|
|
const sub = redisClient.duplicate(); // duplicate to keep separate pub/sub
|
|
await sub.connect();
|
|
|
|
await sub.subscribe(
|
|
['attached_disks', 'host_stats'],
|
|
(message, channel) => { // <-- single handler
|
|
let payload;
|
|
try {
|
|
payload = JSON.parse(message); // message is a JSON string
|
|
} catch (e) {
|
|
console.error(`Failed to parse ${channel}`, e);
|
|
return;
|
|
}
|
|
|
|
io.emit(channel, payload);
|
|
}
|
|
);
|
|
|
|
sub.on('error', err => console.error('Subscriber error', err));
|
|
})();
|
|
|
|
// ---------- Socket.io ----------
|
|
io.on('connection', socket => {
|
|
console.log('client connected:', socket.id);
|
|
// Optional: send the current state on connect if you keep it cached
|
|
});
|
|
|
|
// ---------- Start ----------
|
|
const PORT = process.env.PORT || 3000;
|
|
server.listen(PORT, () => {
|
|
console.log(`Server listening on http://localhost:${PORT}`);
|
|
}); |