-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
52 lines (43 loc) · 1.31 KB
/
Copy pathserver.js
File metadata and controls
52 lines (43 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
46
47
48
49
50
51
52
const WebSocket = require('ws');
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
});
} else {
res.writeHead(404);
res.end();
}
});
const wss = new WebSocket.Server({ server });
let ideas = [];
wss.on('connection', (ws) => {
console.log('Client connected');
ws.send(JSON.stringify(ideas));
ws.on('message', (message) => {
console.log('Received:', message.toString());
const idea = message.toString();
if (typeof idea === "string") {
ideas.push(idea);
}
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(ideas));
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
server.listen(3000, () => {
console.log('Server is listening on http://localhost:3000');
});