This repository was archived by the owner on Jun 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocketServer.js
More file actions
75 lines (67 loc) · 2.13 KB
/
socketServer.js
File metadata and controls
75 lines (67 loc) · 2.13 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
module.exports = (Server, server, instrument) => {
const usersOnline = new Map();
const rooms = [];
const io = new Server(server, {
cors: {
origin: ["http://localhost:3000", "https://admin.socket.io"],
methods: ["GET", "POST"],
transports: ["websocket", "polling"],
credentials: true,
},
allowEIO3: true,
});
io.on("connection", (socket) => {
console.log(`user is connected on socket ${socket.id}`);
socket.on("user register", (data) => {
if (!usersOnline.has(data.username) && data.username !== undefined) {
// register user and announce to rooms joined
data.id = socket.id;
usersOnline.set(data.username, data);
socket.join(data.rooms);
socket
.to(data.rooms[0])
.emit(
"new user",
`${data.username} has joined the room ${data.rooms[0]}`
);
} else {
// anounce user return arrival and isssue new socket ID
let user = usersOnline.get(data.username);
user.id = socket.id;
socket.join(data.rooms);
socket
.to(data.rooms[0])
.emit("user online", `${data.username} is back online`);
}
console.log(usersOnline);
});
socket.on("post denied", (id , content) => {
socket.broadcast.emit("post denied", id);
if (usersOnline.has(content.author)) {
let user = usersOnline.get(content.author);
socket.to(user.id).emit("post denied notice", content);
}
});
socket.on("post approved", (id, content) => {
socket.broadcast.emit("post approved", id);
if (usersOnline.has(content.author)) {
let user = usersOnline.get(content.author);
socket.to(user.id).emit("post approved notice", content);
}
});
socket.on("new post", (data) => {
socket.broadcast.emit("new post", data);
});
socket.on("disconnect", () => {
// log time of disconnection
console.log(
`the socket ${socket.id} has disconnected at ${new Date(
Date.now()
).toLocaleTimeString()}`
);
});
});
instrument(io, {
auth: false,
});
};