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/ConnectionGetter.scala | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/main/scala/Server/ConnectionGetter.scala (limited to 'src/main/scala/Server/ConnectionGetter.scala') diff --git a/src/main/scala/Server/ConnectionGetter.scala b/src/main/scala/Server/ConnectionGetter.scala new file mode 100644 index 0000000..b3246a7 --- /dev/null +++ b/src/main/scala/Server/ConnectionGetter.scala @@ -0,0 +1,25 @@ +package o1game.Server + +import java.io.IOException +import java.net.{ServerSocket, Socket} +import scala.concurrent.Future +import scala.util.{Failure, Success} +import scala.concurrent.ExecutionContext.Implicits.global + +/** Small helper class for getting new connections using futures */ +class ConnectionGetter(val socket: ServerSocket): + + private var nextClient: Future[Socket] = Future.failed(IOException()) + + /** Returns a new socket to a client if there is any new connections. */ + 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 -- cgit v1.2.3