» Node.js: Make Web Chat App with Socket.IO » 2. Development » 2.4 Group Messages

Group Messages

Create Group

A Socket.IO room is a virtual concept that allows you to group sockets (connections) together. Sockets that are in the same room can communicate with each other easily. This feature is very useful when you want to broadcast messages to specific groups of clients, rather than broadcasting to all connected clients.

Changes in app.js:

@@ -30,6 +30,15 @@ io.on("connection", (socket) => {
     const { to } = data;
     io.to(to).emit("chat", data);
   });
+
+  // Create Room
+  socket.on("create-group", (data) => {
+    const { sids: socketIds, name: roomName, id: roomId } = data;
+    socketIds.forEach((socketId) => {
+      io.sockets.sockets.get(socketId)?.join(roomId);
+    });
+    console.log(`Room ${roomId} => ${roomName} created`);
+  });
 });
 
 // Start the server
  • sids has all the socket IDs of users in a to-be-created group.
  • roomId is a unique alphanumeric string, which is more suitable than a user inputed room name here.

Forward Group Messages

@@ -31,12 +31,18 @@ io.on("connection", (socket) => {
     io.to(to).emit("chat", data);
   });
 
+  socket.on("group-chat", (data) => {
+    const { room } = data;
+    io.to(room).except(socket.id).emit("group-chat", data);
+  });
+
   // Create Room
   socket.on("create-group", (data) => {
     const { sids: socketIds, name: roomName, id: roomId } = data;
     socketIds.forEach((socketId) => {
       io.sockets.sockets.get(socketId)?.join(roomId);
     });
+    io.to(roomId).emit("create-group", data);
     console.log(`Room ${roomId} => ${roomName} created`);
   });
 });

io.to(...).except(...) forwards the messages to all the participants in the room except the sender.

io.to(roomId).emit("create-group", ...) notifies all the participants that a new group has been created.

PrevNext