Broadcast 广播消息给所有成员 (包括发送者)
(ctx context.Context, text string)
| 161 | |
| 162 | // Broadcast 广播消息给所有成员 (包括发送者) |
| 163 | func (r *Room) Broadcast(ctx context.Context, text string) error { |
| 164 | r.mu.RLock() |
| 165 | |
| 166 | // 复制成员列表 |
| 167 | targets := make(map[string]string, len(r.members)) |
| 168 | maps.Copy(targets, r.members) |
| 169 | |
| 170 | r.mu.RUnlock() |
| 171 | |
| 172 | // 记录到历史 |
| 173 | msg := RoomMessage{ |
| 174 | From: "system", |
| 175 | Text: text, |
| 176 | Sent: nowTimestamp(), |
| 177 | } |
| 178 | |
| 179 | r.mu.Lock() |
| 180 | r.history = append(r.history, msg) |
| 181 | r.mu.Unlock() |
| 182 | |
| 183 | // 发送消息 |
| 184 | for _, agentID := range targets { |
| 185 | ag, exists := r.pool.Get(agentID) |
| 186 | if !exists { |
| 187 | continue |
| 188 | } |
| 189 | |
| 190 | go func(agent *agent.Agent, txt string) { |
| 191 | _ = agent.Send(ctx, txt) |
| 192 | }(ag, text) |
| 193 | } |
| 194 | |
| 195 | return nil |
| 196 | } |
| 197 | |
| 198 | // SendTo 发送消息给指定成员 |
| 199 | func (r *Room) SendTo(ctx context.Context, from string, to string, text string) error { |