-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
45 lines (35 loc) · 1.31 KB
/
server.js
File metadata and controls
45 lines (35 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const express = require('express');
const path = require('path');
const http = require('http');
const { WebSocketServer } = require('ws');
const app = express();
const PORT = process.env.PORT || 3000;
// Serve static files from the "public" folder
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/view', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'view.html'));
});
// Create HTTP server (Express doesn't create one by default for WebSocket attachment)
const server = http.createServer(app);
// Attach WebSocket server on /ws (Render and many proxies expect a dedicated path)
const wss = new WebSocketServer({ server, path: '/ws' });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (data) => {
// Broadcast to every other connected client (so both pages stay in sync)
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === 1) {
client.send(data.toString());
}
});
});
ws.on('close', () => console.log('Client disconnected'));
});
server.listen(Number(PORT), '0.0.0.0', () => {
console.log(`Server running on port ${PORT}`);
console.log(' Drag page: /');
console.log(' View page: /view');
});