-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.js
42 lines (34 loc) · 1.14 KB
/
socket.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
// import { server } from ".";
// import { Server } from "socket.io";
// const io = new Server(server, {
// cors: {
// origin: "http://localhost:3000",
// },
// });
const socketIo = (io) => {
let activeUsers = [];
io.on("connection", (socket) => {
socket.on("new-user-add", (newUserId) => {
if (!activeUsers.some((user) => user.userId === newUserId)) {
activeUsers.push({ userId: newUserId, socketId: socket.id });
// console.log("New User Connected", activeUsers);
}
io.emit("get-users", activeUsers);
});
socket.on("disconnect", () => {
activeUsers = activeUsers.filter((user) => user.socketId !== socket.id);
// console.log("User Disconnected", activeUsers);
io.emit("get-users", activeUsers);
});
socket.on("send-message", (data) => {
const { receiverId } = data;
const user = activeUsers.find((user) => user.userId === receiverId);
// console.log("Sending from socket to :", receiverId);
// console.log("Data: ", data);
if (user) {
io.to(user.socketId).emit("recieve-message", data);
}
});
});
};
export default socketIo;