const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const path = require('path'); const app = express(); const port = 8080; // Serve static files (if any) app.use(express.static('public')); // Data structures to store client data const clients = {}; // HTTP server const server = http.createServer(app); // WebSocket server const wss = new WebSocket.Server({ server }); // Handle new WebSocket connections wss.on('connection', (ws) => { let clientId = null; ws.on('message', (message) => { try { const data = JSON.parse(message); if (!clientId && data.clientId) { clientId = data.clientId; clients[clientId] = { ws: ws, html: '', css: '', url: '' }; console.log(`Client ${clientId} connected`); } if (data.type === 'pageContent') { clients[clientId].html = data.html; clients[clientId].css = data.css; clients[clientId].url = data.url; } else if (data.type === 'keyboardEvent') { // Relay the keyboard event to other clients relayKeyboardEvent(data, clientId); } } catch (e) { console.error('Error parsing message:', e); } }); ws.on('close', () => { console.log(`Client ${clientId} disconnected`); delete clients[clientId]; }); }); // Function to relay keyboard events to other clients function relayKeyboardEvent(data, senderId) { // Send the keyboard event to all connected clients except the sender for (const [id, client] of Object.entries(clients)) { if (id !== senderId) { client.ws.send(JSON.stringify(data)); } } } // Route to list all active clients app.get('/clients', (req, res) => { res.json(Object.keys(clients)); }); // Route to render the client's page app.get('/client/:id', (req, res) => { const client = clients[req.params.id]; if (client) { let htmlContent = client.html; // Inject the CSS into a style tag in the head const cssTag = ``; htmlContent = htmlContent.replace('', `${cssTag}`); // Inject the script to establish WebSocket connection const scriptTag = ` `; htmlContent = htmlContent.replace('', `${scriptTag}`); res.send(htmlContent); } else { res.status(404).send('Client not found'); } }); // Start the server server.listen(port, () => { console.log(`Server is listening on http://localhost:${port}`); });