-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (66 loc) · 1.8 KB
/
index.js
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
69
70
71
72
73
74
75
76
77
78
79
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
connectionStateRecovery: {},
cors: {
origin: "http://localhost:4200",
},
});
const cors = require("cors");
app.use(cors());
const PORT = process.env.PORT || 3000;
io.on("connection", (socket) => {
console.log("A user connected");
socket.on("createRoom", () => {
const roomId = generateRoomId();
socket.join(roomId);
socket.emit("roomCreated", roomId);
});
socket.on("joinRoom", (roomId) => {
const isRoomExist = io.sockets.adapter.rooms.has(roomId);
if (isRoomExist) {
const users = io.sockets.adapter.rooms.get(roomId);
if (users.size === 1) {
socket.join(roomId);
io.to(roomId).emit("gameStart", {
roomId,
users: [...users],
});
} else {
socket.emit("roomFull");
}
} else {
socket.emit("noRoom");
}
});
socket.on("disconnect", async () => {
const rooms = io.sockets.adapter.rooms;
[...rooms].forEach((room) => {
socket.to(room).emit("userLeft", `User ${socket.id} has left the room`);
});
console.log("User disconnected");
});
socket.on("boardClick", async (data) => {
io.to(data.roomId).emit("boardData", data);
});
socket.on("reset", async (data) => {
socket.to(data.roomId).emit("restartGame");
});
socket.on("userLeft", async (data) => {
socket.to(data.roomId).emit("leftGame");
});
});
app.get("/", (req, res) => {
res.send({
hi: "kem chho?",
});
});
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
function generateRoomId() {
return Math.random().toString(36).substr(2, 6) + new Date().getSeconds();
}