diff options
Diffstat (limited to 'src/main/scala/Server/Client.scala')
-rw-r--r-- | src/main/scala/Server/Client.scala | 27 |
1 files changed, 26 insertions, 1 deletions
diff --git a/src/main/scala/Server/Client.scala b/src/main/scala/Server/Client.scala index c7ff075..3bc4012 100644 --- a/src/main/scala/Server/Client.scala +++ b/src/main/scala/Server/Client.scala @@ -1,6 +1,7 @@ package o1game.Server import java.net.Socket +import scala.util.Try import scala.math.min import o1game.constants.* @@ -69,12 +70,36 @@ class Clients(maxClients: Int): this.clients(i) = Some(client) true + /** Returns all the clients. + * + * @return an iterable of all the clients + */ def allClients: Iterable[Client] = clients.toVector.flatten + + /** Applies the function `f` to all the clients for its side effects. */ def foreach(f: Client => Any): Unit = this.clients.flatten.foreach(f) + + /** Applies the function `f` to all the clients for its side effects + * and removes all the clients for which `f([client])` returns false. + * This is useful for doing IO with the client and removing clients + * with stale sockets. + * + * @param f the function to apply to all the clients and filter them with + */ def removeNonSatisfying(f: Client => Boolean): Unit = for i <- this.clients.indices do this.clients(i) match case Some(c) => if !f(c) then this.clients(i) = None - case None =>
\ No newline at end of file + case None => + + /** Applies the function f to all clients for its side effects. + * If the function throws an exception, the client is removed. + * Probably a more concise alternative to `removeNonSatisfying`, + * but might catch exceptions unintentionally. + * + * @param f the function to apply for its side effects to each client + */ + def mapAndRemove(f: Client => Unit): Unit = + this.removeNonSatisfying(c => Try(f(c)).isSuccess)
\ No newline at end of file |