Pepguy's picture
Update app.js
03315c7 verified
raw
history blame
3.88 kB
// 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(`<!doctype html>
<html>
<head>
<title>Dubem Realtime Rooms</title>
<meta charset="utf-8" />
<style>
body { font-family: sans-serif; padding: 20px; background: #f0f0f0; }
#log { border: 1px solid #ccc; height: 200px; overflow-y: auto; padding: 10px; background: #fff; }
input, button { margin: 5px 0; padding: 8px; font-size: 16px; }
</style>
</head>
<body>
<h2>Join a Room & Send Messages</h2>
<input id="room" placeholder="Room ID" />
<button onclick="joinRoom()">Join Room</button>
<div id="log"></div>
<input id="msg" placeholder="Type a message" style="width:80%;" />
<button onclick="sendMsg()">Send</button>
<script>
let ws;
let currentRoom = null;
window.addEventListener('load', () => {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
ws = new WebSocket(\`\${scheme}://\${location.host}\`);
ws.onopen = () => {
log('🔌 Connected to server');
};
ws.onmessage = ({ data }) => {
const msg = JSON.parse(data);
log(\`[\${msg.roomId}] \${msg.message}\`);
};
ws.onclose = () => {
log('❌ Disconnected from server');
};
ws.onerror = err => {
log('⚠️ WebSocket error: ' + err.message);
};
});
function joinRoom() {
const roomId = document.getElementById('room').value.trim();
if (!roomId) return alert('Please enter a room ID');
if (!ws || ws.readyState !== WebSocket.OPEN) {
return alert('Socket not open yet!');
}
ws.send(JSON.stringify({ action: 'join', roomId }));
currentRoom = roomId;
log('➡️ Joined room: ' + roomId);
}
function sendMsg() {
const txt = document.getElementById('msg').value.trim();
if (!txt) return;
if (!ws || ws.readyState !== WebSocket.OPEN) {
return alert('Socket not open yet!');
}
if (!currentRoom) {
return alert('Please join a room first');
}
ws.send(JSON.stringify({
action: 'post',
roomId: currentRoom,
message: txt
}));
document.getElementById('msg').value = '';
}
function log(t) {
const el = document.getElementById('log');
el.innerHTML += '<div>' + t + '</div>';
el.scrollTop = el.scrollHeight;
}
</script>
</body>
</html>`);
});
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}`));