Monorepo for Aesthetic.Computer aesthetic.computer
at main 42 lines 1.3 kB view raw
1// Server 2 3const WebSocket = require("ws"); 4 5const wss = new WebSocket.Server({ port: 8080 }); 6let clients = []; 7let playing = false; 8let canRestart = true; 9 10wss.on("connection", (ws) => { 11 clients.push(ws); 12 ws.on("message", (message) => { 13 const msg = message.toString(); 14 console.log(msg, clients.length); 15 if (msg === "start" && clients.length > 1) { 16 // Make sure this isn't the first connected client, and then 17 // if this is the first client to start the video, 18 // broadcast a 'play' message to all clients. 19 if (!playing) { 20 playing = true; 21 clients.forEach((client) => { 22 if (client.readyState === WebSocket.OPEN) { 23 client.send("play"); 24 } 25 }); 26 } 27 } else if (msg === "restart" && canRestart) { 28 // Broadcast a 'restart' message to all clients to trigger 29 // the video playback to start over 30 clients.forEach((client) => { 31 if (client.readyState === WebSocket.OPEN) client.send("restart"); 32 }); 33 canRestart = false; 34 // Prevent double restarts by adding a .5 second buffer. 35 setTimeout(() => (canRestart = true), 500); 36 } 37 }); 38 39 ws.on("close", () => { 40 clients = clients.filter((client) => client !== ws); // Remove on close. 41 }); 42});