RequestUsername
handling
def registerAndGreet(name: String, client: Client, state: State): IO[Unit] =
state.register(name, client) >>
client.write(ServerCommand.SetUsername(name)) >>
state.broadcast(ServerCommand.Alert(s"$name connected"))
Client
handling
def handleClient(state: State)(client: Client): Stream[IO, Unit] = {
def waitForUsername(s: Stream[IO, ClientCommand]): Pull[IO, Unit, Unit] =
s.pull.uncons1.flatMap {
case Some((ClientCommand.RequestUsername(name), restOfTheCommands)) =>
Pull.eval(registerAndGreet(name, client, state)) >>
handleMessages(name, state, client.write, restOfTheCommands).pull.echo
case Some((_, rest)) => waitForUsername(rest)
case None => Pull.done
}
waitForUsername(client.read).stream
}
Pull[IO, Unit, Option[(ClientCommand, Stream[IO, ClientCommand])]]