-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
51 lines (40 loc) · 1.18 KB
/
Copy pathserver.js
File metadata and controls
51 lines (40 loc) · 1.18 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
const { createServer } = require("http");
const next = require("next");
const { Server } = require("socket.io");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
let waitingUser = null;
app.prepare().then(() => {
const httpServer = createServer((req, res) => {
handle(req, res);
});
const io = new Server(httpServer);
io.on("connection", (socket) => {
console.log("User connected:", socket.id);
socket.on("find_match", () => {
if (!waitingUser) {
waitingUser = socket;
socket.emit("waiting");
} else {
const roomId = `room_${waitingUser.id}_${socket.id}`;
socket.join(roomId);
waitingUser.join(roomId);
io.to(roomId).emit("matched", {
roomId,
users: [waitingUser.id, socket.id],
});
waitingUser = null;
}
});
socket.on("disconnect", () => {
if (waitingUser?.id === socket.id) {
waitingUser = null;
}
console.log("User disconnected:", socket.id);
});
});
httpServer.listen(3000, () => {
console.log("🚀 Server running at http://localhost:3000");
});
});