-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
170 lines (141 loc) · 5.49 KB
/
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
const { createServer } = require("node:http");
const next = require("next");
const { Server } = require("socket.io");
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = process.env.PORT || 3000;
const app = next({ dev, hostname, port });
const handler = app.getRequestHandler();
global.onlineUsers = new Map();
global.activeChatRooms = new Map();
app.prepare().then(() => {
const httpServer = createServer(handler);
const io = new Server(httpServer, {
maxHttpBufferSize: 1e8, // Increase maximum HTTP buffer size
pingTimeout: 60000, // Set the ping timeout to 60 seconds
transports: ["websocket", "polling"], // Allow both WebSocket and long polling transports
});
io.on("connection", (socket) => {
global.chatSocket = socket;
socket.on("add-user", (userId) => {
onlineUsers.set(userId, socket.id);
io.emit("online-users", {
onlineUsers: Array.from(onlineUsers.keys()),
});
});
socket.on("send-msg", (data) => {
const { recieverUser, message, chatRoomId, senderUser } = data;
const sendUserSocket = onlineUsers.get(recieverUser._id);
if (sendUserSocket) {
socket.to(sendUserSocket).emit("msg-recieve", data);
}
});
// When a user joins the chatroom
socket.on("join", ({ chatRoomId, userId }) => {
socket.join(chatRoomId);
// If the chatRoom does not exist yet, initialize it with a new Set for users
if (!activeChatRooms.has(chatRoomId)) {
activeChatRooms.set(chatRoomId, new Set());
}
// Get the current users in the room and add the new user
const usersInRoom = activeChatRooms.get(chatRoomId);
usersInRoom.add(userId);
// Broadcast updated room info to all clients
io.emit("active-chatRooms", {
activeChatRooms: Array.from(activeChatRooms.keys()).map((roomId) => ({
roomId,
users: Array.from(activeChatRooms.get(roomId)), // All users in this room
})),
});
});
//When a user leaves the chatroom
socket.on("leave", ({ chatRoomId, userId }) => {
socket.leave(chatRoomId);
// Get the users in the room and remove the user who left
const usersInRoom = activeChatRooms.get(chatRoomId);
if (usersInRoom) {
usersInRoom.delete(userId); // Remove the user from the room
// If no users are left in the room, remove the room entirely
if (usersInRoom.size === 0) {
activeChatRooms.delete(chatRoomId);
}
}
// Broadcast updated room info to all clients
io.emit("active-chatRooms", {
activeChatRooms: Array.from(activeChatRooms.keys()).map((roomId) => ({
roomId,
users: Array.from(activeChatRooms.get(roomId)), // All users in this room
})),
});
});
socket.on("sign-out", (id) => {
// Find the user by socket ID and remove them from onlineUsers
let disconnectedUserId = id;
onlineUsers.delete(id); // Remove the user from the map
if (disconnectedUserId) {
// Loop through all chat rooms to remove the user from each room they were part of
activeChatRooms.forEach((usersInRoom, chatRoomId) => {
if (usersInRoom.has(disconnectedUserId)) {
usersInRoom.delete(disconnectedUserId); // Remove user from the room
// If the room is empty, delete the room
if (usersInRoom.size === 0) {
activeChatRooms.delete(chatRoomId);
}
}
});
// Emit updated room info to all clients after the user has been removed
io.emit("active-chatRooms", {
activeChatRooms: Array.from(activeChatRooms.keys()).map((roomId) => ({
roomId,
users: Array.from(activeChatRooms.get(roomId)), // All users in this room
})),
});
}
// Emit the updated online users list to all clients
io.emit("online-users", {
onlineUsers: Array.from(onlineUsers.keys()),
});
});
socket.on("disconnect", () => {
// Find the user by socket ID and remove them from onlineUsers
let disconnectedUserId;
onlineUsers.forEach((value, key) => {
if (value === socket.id) {
disconnectedUserId = key;
onlineUsers.delete(key); // Remove the user from the map
}
});
if (disconnectedUserId) {
// Loop through all chat rooms to remove the user from each room they were part of
activeChatRooms.forEach((usersInRoom, chatRoomId) => {
if (usersInRoom.has(disconnectedUserId)) {
usersInRoom.delete(disconnectedUserId); // Remove user from the room
// If the room is empty, delete the room
if (usersInRoom.size === 0) {
activeChatRooms.delete(chatRoomId);
}
}
});
// Emit updated room info to all clients after the user has been removed
io.emit("active-chatRooms", {
activeChatRooms: Array.from(activeChatRooms.keys()).map((roomId) => ({
roomId,
users: Array.from(activeChatRooms.get(roomId)), // All users in this room
})),
});
}
// Emit the updated online users list to all clients
io.emit("online-users", {
onlineUsers: Array.from(onlineUsers.keys()),
});
});
});
httpServer
.once("error", (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});