// server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const rooms = new Map();
app.get('/', (req, res) => {
res.send(`
Dubem Realtime Rooms
Join a Room & Send Messages
`);
});
wss.on('connection', ws => {
// When a client sends a 'join', we remove it from ALL rooms first
ws.on('message', raw => {
let msg;
try { msg = JSON.parse(raw); } catch { return; }
if (msg.action === 'join' && msg.roomId) {
// leave all existing rooms
for (const clients of rooms.values()) {
clients.delete(ws);
}
// join the new room
const room = msg.roomId;
if (!rooms.has(room)) rooms.set(room, new Set());
rooms.get(room).add(ws);
return;
}
if (msg.action === 'post' && msg.roomId && msg.message) {
const clients = rooms.get(msg.roomId);
if (!clients) return;
const payload = JSON.stringify({
roomId: msg.roomId,
message: msg.message,
timestamp: Date.now()
});
for (const client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(payload);
}
}
}
});
ws.on('close', () => {
// remove from all rooms on disconnect
for (const clients of rooms.values()) {
clients.delete(ws);
}
});
});
const PORT = process.env.PORT || 8000
//7860;
server.listen(PORT, () => console.log(`✅ Activity server running at http://localhost:${PORT}`));