-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (60 loc) · 1.83 KB
/
server.js
File metadata and controls
72 lines (60 loc) · 1.83 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import http from "http";
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
console.log("WebSocket server running on ws://localhost:8080");
wss.on("connection", ws => {
ws.send(JSON.stringify({ message: "Welcome to realtime server!" }));
ws.on("message", raw => {
const data = JSON.parse(raw);
console.log("Message received:", data);
// Broadcast to all clients
wss.clients.forEach(client => {
if (client.readyState === ws.OPEN) {
client.send(JSON.stringify(data));
}
});
});
});
const server = http.createServer((req, res) => {
if (req.method === "POST" && req.url === "/broadcast") {
console.log("Received broadcast request");
let body = "";
req.on("data", chunk => body += chunk);
req.on("end", () => {
try {
const data = JSON.parse(body);
console.log("data to broadcast:", data);
console.log("Number of connected clients:", wss.clients.size);
// broadcast to all ws clients
wss.clients.forEach(client => {
console.log("Broadcasting to client");
client.send(JSON.stringify(data));
});
res.writeHead(200);
res.end("OK");
} catch (e) {
res.writeHead(400);
res.end("Invalid JSON..." + e.message);
}
});
}
});
server.listen(3001, () => {
console.log("HTTP endpoint: http://localhost:3001/broadcast");
});
/*
setInterval(() => {
const message = {
type: "task-created",
task: {
id: Math.floor(Math.random() * 1000),
title: "New Task " + Date.now(),
x: (new Date()).toLocaleTimeString(),
y: Math.floor(Math.random() * 500)
}
};
for (const client of wss.clients) {
client.send(JSON.stringify(message));
}
}, 1000);
*/