-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
69 lines (63 loc) · 1.48 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
const express = require("express");
const cors = require("cors");
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server);
const rooms = {};
app.use(express.json());
app.use(cors());
app.get("/api/rooms", (req, res) => {
res.json(rooms);
});
app.get("/api/ping", (req, res, next) => {
res.json({ ping: "pong" });
});
io.on("connection", (socket) => {
const id = socket.handshake.query.id;
socket.join(id);
socket.on("create-room", (user) => {
try {
rooms[user.id] = { 0: user };
io.emit("room-created", rooms);
socket.join(user.id);
} catch (error) {
console.log(error);
}
});
socket.on("join-room", (roomId, user) => {
try {
rooms[roomId][1] = user;
io.emit("room-created", rooms);
socket.join(roomId);
} catch (error) {
console.log(error);
}
});
socket.on("send-turn", (roomId, state) => {
try {
socket.to(roomId).broadcast.emit("turn", state);
} catch (error) {
console.log(error);
}
});
socket.on("close-room", () => {
try {
delete rooms[id];
io.emit("room-created", rooms);
} catch (error) {
console.log(error);
}
});
socket.on("disconnect", () => {
try {
delete rooms[id];
io.emit("room-created", rooms);
} catch (error) {
console.log(error);
}
});
});
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
console.log(`app running on port ${PORT}`);
});