Files
cosmoserver/files/web/node_server/server.js
2026-03-09 16:32:43 -07:00

70 lines
1.8 KiB
JavaScript

// server.js
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();
const sub = redisClient.duplicate(); // duplicate to keep separate pub/sub
await sub.connect();
// Subscribe to the channel that sends host stats
await sub.subscribe(
['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);
}
);
// Subscribe to the channel that sends history stats
await sub.subscribe(
['history_stats'],
(message, channel) => {
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}`);
});