aboutsummaryrefslogtreecommitdiff
path: root/src/scalevalapokalypsi/Server/ConnectionGetter.scala
blob: 40830c70c72733094cbf173a5fbdca738243319f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package scalevalapokalypsi.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