» Node.js: Make Web Chat App with Socket.IO » 2. Development » 2.2 Contacts

Contacts

Use a Map to store all the users in the memory.

You need to use databases for large-scale projects.

Update app.js:

@@ -10,9 +10,21 @@ const io = new Server(server, {
   },
 });
 
+// Use a Map to store all connected users
+const users = new Map();
+
 // Handle incoming socket connections
 io.on("connection", (socket) => {
-  console.log("A user connected", socket.id);
+  socket.on("user-join", (user) => {
+    if (!user.name) {
+      return;
+    }
+    console.log(`User ${socket.id} => ${user.emoji} ${user.name} joined`);
+    users.set(socket.id, { ...user, sid: socket.id });
+
+    // Broadcast to all connected clients
+    io.emit("contacts", Array.from(users.entries()));
+  });
 });
 
 // Start the server

io.emit will broadcast the latest contact list to all the users.

PrevNext