mirror of
https://gitlab.com/wgp/dougal/software.git
synced 2025-12-06 08:27:08 +00:00
Basic implementation. It assigns a random ID to every connection and passes details of every connection to everyone else.
63 lines
1.2 KiB
JavaScript
63 lines
1.2 KiB
JavaScript
|
|
|
|
const connections = [];
|
|
|
|
function broadcast (message, sender) {
|
|
message.rtc = true;
|
|
const body = JSON.stringify(message);
|
|
for (const socket of connections) {
|
|
if (socket != sender) {
|
|
socket.send(body);
|
|
}
|
|
}
|
|
}
|
|
|
|
function unicast (message, socket) {
|
|
message.rtc = true;
|
|
socket.send(JSON.stringify(message));
|
|
}
|
|
|
|
function addConnection (socket) {
|
|
if (!connections.includes(socket)) {
|
|
const peerId = Math.round(Math.random()*1000000000);
|
|
const otherPeers = connections.map(c => c.peerId);
|
|
broadcast({newPeer: peerId}, socket);
|
|
unicast({peerId, otherPeers}, socket);
|
|
socket.peerId = peerId;
|
|
connections.push(socket);
|
|
}
|
|
}
|
|
|
|
function removeConnection (socket) {
|
|
const pos = connections.indexOf(socket);
|
|
|
|
if (pos != -1) {
|
|
connections.splice(pos, 1);
|
|
}
|
|
}
|
|
|
|
function handler (socket, message) {
|
|
try {
|
|
const payload = JSON.parse(message);
|
|
if (payload.rtc === true) {
|
|
console.log("RTC Message", payload);
|
|
if ("to" in payload) {
|
|
const dest = connections.find(c => c.peerId == payload.to);
|
|
if (dest) {
|
|
unicast(payload, dest);
|
|
}
|
|
} else {
|
|
broadcast(payload, socket);
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.error("Invalid message", message, err);
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
addConnection,
|
|
removeConnection,
|
|
handler
|
|
};
|