» Go: 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 main.go:

@@ -56,6 +56,26 @@ func main() {
 			}
 			io.Sockets().To(socket.Room(to)).Emit("chat", data)
 		})
+
+		// Create Room
+		client.On("create-group", func(args ...any) {
+			data, ok := args[0].(Data)
+			if !ok {
+				return
+			}
+			socketIds := data["sids"].([]interface{})
+			var individualRooms []socket.Room
+			for _, socketId := range socketIds {
+				individualRooms = append(individualRooms, socket.Room(socketId.(string)))
+			}
+			roomName := data["name"].(string)
+			roomId := data["id"].(string)
+			// Join Room
+			io.Sockets().In(individualRooms...).SocketsJoin(socket.Room(roomId))
+			// Broadcast to all participants
+			io.Sockets().To(socket.Room(roomId)).Emit("create-group", data)
+			fmt.Printf("Room %s => %s created\n", roomId, roomName)
+		})
 	})
 
 	http.Handle("/socket.io/", io.ServeHandler(nil))
  • 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.

io.Sockets().To(socket.Room(roomId)).Emit(...) notifies all the participants that a new group has been created.

Forward Group Messages

Changes in main.go:

@@ -76,6 +76,18 @@ func main() {
 			io.Sockets().To(socket.Room(roomId)).Emit("create-group", data)
 			fmt.Printf("Room %s => %s created\n", roomId, roomName)
 		})
+
+		client.On("group-chat", func(args ...any) {
+			data, ok := args[0].(Data)
+			if !ok {
+				return
+			}
+			roomId, ok := data["room"].(string)
+			if !ok {
+				return
+			}
+			io.Sockets().To(socket.Room(roomId)).Except(socket.Room(client.Id())).Emit("group-chat", data)
+		})
 	})
 
 	http.Handle("/socket.io/", io.ServeHandler(nil))

io.Sockets().To(...).Except(socket.Room(client.Id())).Emit(...) forwards the messages to all the participants in the room except the sender.

PrevNext