-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
68 lines (61 loc) · 2.34 KB
/
server.js
File metadata and controls
68 lines (61 loc) · 2.34 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
const WebSocket = require("ws");
const wss = new WebSocket.Server({ port: 8080 });
let streams = []; // {id, title, user, category}
const generateID = () => Math.random().toString(36).substr(2, 9);
function broadcast(data, exclude) {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN && client !== exclude) {
client.send(JSON.stringify(data));
}
});
}
wss.on("connection", (ws) => {
ws.id = generateID();
ws.on("message", (msg) => {
try {
const data = JSON.parse(msg);
if (data.type === "chat") {
broadcast({ type: "chat", chat: data.chat, user: data.user }, ws);
}
else if (data.type === "newStream") {
const streamID = generateID();
const stream = {
id: streamID,
title: data.title,
user: data.user,
category: data.category,
};
streams.push(stream);
ws.stream = stream;
broadcast({ type: "streamsUpdate", streams });
}
else if (data.type === "stopStream") {
streams = streams.filter((s) => s.id !== ws.stream?.id);
broadcast({ type: "streamsUpdate", streams });
}
else if (data.type === "search") {
const q = data.query.toLowerCase();
const results = streams.filter(
(s) => s.title.toLowerCase().includes(q)
);
ws.send(JSON.stringify({ type: "searchResults", results }));
}
else if (data.type === "getStreamByID") {
const stream = streams.find((s) => s.id === data.id);
ws.send(JSON.stringify({ type: "streamByID", stream }));
}
else if (data.type === "offer" || data.type === "answer" || data.type === "iceCandidate") {
broadcast(data, ws);
}
} catch (e) {
console.error("Invalid message", e);
}
});
ws.on("close", () => {
if (ws.stream) {
streams = streams.filter((s) => s.id !== ws.stream.id);
broadcast({ type: "streamsUpdate", streams });
}
});
});
console.log("✅ WebSocket server running on ws://localhost:8080");