-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
49 lines (40 loc) · 1.13 KB
/
Copy pathsocket.js
File metadata and controls
49 lines (40 loc) · 1.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
const { Server } = require("socket.io");
let io;
const userSocketMap = new Map(); // userId -> socketId
module.exports = {
init: (httpServer) => {
io = new Server(httpServer, {
cors: {
origin: "http://localhost:5173",
methods: ["GET", "POST", "PUT", "DELETE"],
},
});
io.on("connection", (socket) => {
console.log("Client connected:", socket.id);
socket.on("register_user", (userId) => {
userSocketMap.set(userId, socket.id);
console.log(`User ${userId} registered with socket ${socket.id}`);
});
socket.on("disconnect", () => {
// Find and remove disconnected socket from map
for (const [userId, socketId] of userSocketMap.entries()) {
if (socketId === socket.id) {
userSocketMap.delete(userId);
console.log(`User ${userId} disconnected`);
break;
}
}
});
});
return io;
},
getIO: () => {
if (!io) {
throw new Error("Socket.io not initialized!");
}
return io;
},
getUserSocket: (userId) => {
return userSocketMap.get(userId?.toString());
}
};