-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket-server.js
59 lines (47 loc) · 1.57 KB
/
socket-server.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
const chatController = require("./app/controllers/chat.controller.js")
module.exports = function(io) {
io.on('connection', async (socket) => {
console.log('a user connected');
socket.emit("connected");
const sendUsersOnline = (roomId) => {
const numUsers = io.sockets.adapter.rooms.get(roomId)?.size || 0;
io.to(roomId).emit('usersOnline', numUsers);
};
socket.on('joinRoom', (roomId) => {
socket.join(roomId);
console.log(`User joined room: ${roomId}`);
sendUsersOnline(roomId)
});
socket.on("message", (msg) => {
msg.fromUser = JSON.stringify(msg.fromUser);
chatController.create(msg)
.then((msg) => {
msg.fromUser = JSON.parse(msg.fromUser)
io.to(msg.roomId).emit('message', msg);
})
.catch((err) => {
console.error(err.message);
})
});
socket.on("privateMessage", (toSocketId, msg) => {
socket.to(toSocketId).emit("privateMessage", socket.id, msg);
});
// socket.on('disconnecting', () => {
// const rooms = Array.from(socket.rooms);
// console.log("\n\n\nROOMS:", socket.rooms);
// rooms.forEach((room) => {
// console.log("\n\n\nROOM:", room);
// sendUsersOnline(room);
// });
// });
socket.on("disconnect", () => {
console.log("User disconnected");
const rooms = Array.from(socket.rooms);
console.log("\n\n\nROOMS:", socket.rooms);
rooms.forEach((room) => {
console.log("\n\n\nROOM:", room);
sendUsersOnline(room);
});
});
});
}