Skip to content

Commit

Permalink
resurrect
Browse files Browse the repository at this point in the history
  • Loading branch information
mattslaney committed Jul 8, 2024
1 parent b0306b8 commit ca236c6
Show file tree
Hide file tree
Showing 5 changed files with 478 additions and 222 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
node_modules
public/scripts/config.js
config.json
23 changes: 21 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,42 @@
const express = require("express");
const app = express();
const http = require("http");
const fs = require("fs");
const server = http.createServer(app);
const port = process.env.PORT || 3000;

const { Server } = require("socket.io");
const io = new Server(server);

let peerConfig = {};
try {
const data = fs.readFileSync("config.json");
peerConfig = JSON.parse(data);
} catch (err) {
console.error("Error reading config file: ", err);
}

io.on("connection", (socket) => {
socket.emit("welcome");
console.debug("New connection: ", socket.id);

socket.on("join", (code) => {
if (!io.sockets.adapter.rooms.get(code)) {
//First client - create
socket.join(code);
socket.emit("created");
socket.emit("created", code);
console.debug("First client: ", code);
} else if (io.sockets.adapter.rooms.get(code).size === 1) {
//Second client - join
socket.join(code);
socket.emit("joined");
socket.emit("joined", code);
io.to(code).emit("begin");
console.debug("Second client: ", code);
} else {
//Room full - full
socket.emit("full", code);
socket.emit("welcome");
console.debug("Room full: ", code);
}
});

Expand All @@ -37,10 +50,16 @@ io.on("connection", (socket) => {

io.on("disconnecting", (socket) => {
io.to(socket.rooms).emit("bye");
console.debug("Disconnected: ", socket);
});
});

app.use(express.static("public"));

app.get("/config", (_, res) => {
res.json(peerConfig);
});

server.listen(port, () => {
console.log("Server Started.");
console.log(`Listening on http://localhost:${port}`);
Expand Down
Loading

0 comments on commit ca236c6

Please sign in to comment.