-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (60 loc) · 1.58 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
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const cors = require("cors");
const ACTIONS = require("./Action");
const env = require("dotenv").config();
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const port = process.env.PORT || 3001;
app.use(cors());
app.use(express.json());
const userSocketMap = {};
function getAllConnectedmembers(roomid) {
// Map
return Array.from(io.sockets.adapter.rooms.get(roomid) || []).map(
(socketId) => {
return {
socketId,
name: userSocketMap[socketId],
};
}
);
}
io.on("connection", (socket) => {
socket.on(ACTIONS.JOIN, ({ roomid, name }) => {
userSocketMap[socket.id] = name;
socket.join(roomid);
const members = getAllConnectedmembers(roomid);
members.forEach(({ socketId }) => {
io.to(socketId).emit(ACTIONS.JOINED, {
members,
name,
socketId: socket.id,
});
});
});
socket.on(ACTIONS.CODE_CHANGE, ({ roomid, code }) => {
socket.in(roomid).emit(ACTIONS.CODE_CHANGE, {
code,
});
});
socket.on("disconnecting", () => {
const rooms = [...socket.rooms];
rooms.forEach((roomid) => {
socket.in(roomid).emit(ACTIONS.DISCONNECTED, {
socketId: socket.id,
name: userSocketMap[socket.id],
});
});
delete userSocketMap[socket.id];
socket.leave();
});
});
app.get("/", (req, res) => {
res.send({ status: "ok" });
});
server.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});