aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/Server/Client.scala
diff options
context:
space:
mode:
authorJoel Kronqvist <joel.kronqvist@iki.fi>2024-11-05 00:18:36 +0200
committerJoel Kronqvist <joel.kronqvist@iki.fi>2024-11-05 00:18:36 +0200
commit12cbf4d451d1002b8872b0028acbe6bd886ca9bd (patch)
treec8d8ed236cc7ae907f52209cb0dd1f7d40ebf346 /src/main/scala/Server/Client.scala
parentae82027a9bd4e75582f9499d4006b18c29a4129c (diff)
downloadscalevalapokalypsi-12cbf4d451d1002b8872b0028acbe6bd886ca9bd.tar.gz
scalevalapokalypsi-12cbf4d451d1002b8872b0028acbe6bd886ca9bd.zip
Small refactoring
* Moved `ConnectionGetter` to its own file * Added method `mapAndRemove` to Server/Client.scala * Replaced usages of `removeNonSatisfying` with the above * Added some documentation
Diffstat (limited to 'src/main/scala/Server/Client.scala')
-rw-r--r--src/main/scala/Server/Client.scala27
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