From 12cbf4d451d1002b8872b0028acbe6bd886ca9bd Mon Sep 17 00:00:00 2001 From: Joel Kronqvist Date: Tue, 5 Nov 2024 00:18:36 +0200 Subject: 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 --- src/main/scala/Server/Server.scala | 49 +++++++++----------------------------- 1 file changed, 11 insertions(+), 38 deletions(-) (limited to 'src/main/scala/Server/Server.scala') diff --git a/src/main/scala/Server/Server.scala b/src/main/scala/Server/Server.scala index 829010c..1f0cbfc 100644 --- a/src/main/scala/Server/Server.scala +++ b/src/main/scala/Server/Server.scala @@ -6,9 +6,6 @@ package o1game.Server import java.io.IOException import java.lang.Thread.sleep import java.net.{ServerSocket, Socket} -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future -import scala.util.{Failure, Success, Try} import o1game.constants.* /** `Server` exists to initialize a server for the game @@ -47,44 +44,20 @@ class Server(port: Int, maxClients: Int): * @param message the message to send */ private def writeToAll(message: String): Unit = - clients.removeNonSatisfying((c: Client) => - try - val output = c.socket.getOutputStream - output.write(message.toVector.map(_.toByte).toArray) - output.flush() - true - catch - case e: IOException => false + clients.mapAndRemove(c => + val output = c.socket.getOutputStream + output.write(message.toVector.map(_.toByte).toArray) + output.flush() ) /** Reads data sent by clients and stores it in the `Client`s of `clients` */ private def readFromAll(): Unit = - clients.removeNonSatisfying((c: Client) => - try - val input = c.socket.getInputStream - while input.available() != 0 do - val bytesRead = input.read(buffer) - if bytesRead != -1 then - c.receiveData(buffer.take(bytesRead).toVector) - true - catch - case e: IOException => false + clients.mapAndRemove(c => + val input = c.socket.getInputStream + while input.available() != 0 do + val bytesRead = input.read(buffer) + if bytesRead != -1 then + c.receiveData(buffer.take(bytesRead).toVector) ) -end Server - -class ConnectionGetter(val socket: ServerSocket): - - private var nextClient: Future[Socket] = Future.failed(IOException()) - - def newClient(): Option[Socket] = - this.nextClient.value match - case Some(Success(s)) => - nextClient = Future(socket.accept()) - Some(s) - case Some(Failure(e)) => - nextClient = Future(socket.accept()) - None - case None => None - -end ConnectionGetter +end Server \ No newline at end of file -- cgit v1.2.3