From 3cd3634618b72b40bbbdfb40d1019da85c051f81 Mon Sep 17 00:00:00 2001 From: griffi-gh Date: Mon, 13 Feb 2023 02:57:09 +0100 Subject: [PATCH] implement broadcase and multicast functions --- kubi-udp/src/server.rs | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/kubi-udp/src/server.rs b/kubi-udp/src/server.rs index daf4b9a..ad1074c 100644 --- a/kubi-udp/src/server.rs +++ b/kubi-udp/src/server.rs @@ -5,7 +5,7 @@ use std::{ collections::{VecDeque, vec_deque::Drain as DrainDeque}, io::ErrorKind }; -use anyhow::{Result, bail}; +use anyhow::{Result, Error, bail}; use hashbrown::HashMap; use nohash_hasher::BuildNoHashHasher; use crate::{ @@ -137,17 +137,30 @@ impl Server where S: Message, R: Message { Ok(()) } - pub fn send_message(&mut self, id: ClientId, message: S) -> anyhow::Result<()> { + pub fn send_message(&mut self, id: ClientId, message: S) -> Result<()> { self.send_packet(IdServerPacket(Some(id), ServerPacket::Data(message)))?; Ok(()) } - pub fn multicast_message(&mut self, _clients: impl IntoIterator, _message: S) { - todo!() + pub fn multicast_message(&mut self, clients: impl IntoIterator, message: S) -> Vec { + //TODO use actual udp multicast + let mut errors = Vec::with_capacity(0); + for client in clients { + if let Err(error) = self.send_message(client, message.clone()) { + log::error!("Message broadcast failed for id {client}"); + errors.push(error); + } + } + errors } - pub fn broadcast_message(&mut self, _message: S) -> anyhow::Result<()> { - todo!() + pub fn broadcast_message(&mut self, message: S) -> Vec { + let ids = self.clients.keys().copied().collect::>(); + self.multicast_message(ids, message) } - + pub fn broadcast_message_except(&mut self, except: ClientId, message: S) -> Vec { + let ids = self.clients.keys().copied().filter(|&k| k != except).collect::>(); + self.multicast_message(ids, message) + } + pub fn update(&mut self) -> Result<()> { //kick inactive clients self.clients.retain(|&id, client| {