Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. package app
  2.  
  3. import zio._
  4. import zio.clock._
  5. import zio.console._
  6. import zio.random._
  7. import zio.nio.channels.{ AsynchronousServerSocketChannel, AsynchronousSocketChannel }
  8. import zio.nio._
  9. import zio.duration._
  10.  
  11. object Main extends App {
  12.  
  13. def run(args: List[String]): ZIO[Environment, Nothing, Int] =
  14. Server.start(9002)
  15. .foldM(e => putStrLn("Error: " + e.getMessage) *> ZIO.succeed(1), _ => ZIO.succeed(0))
  16. }
  17.  
  18. object Server {
  19.  
  20. def start(port: Int): RIO[Console with Clock with Random, Unit] =
  21. AsynchronousServerSocketChannel().use(
  22. server =>
  23. for {
  24. socketAddress <- SocketAddress.inetSocketAddress(port)
  25. _ <- server.bind(socketAddress)
  26. _ <- putStrLn("Listening on port: " + port)
  27. _ <- server.accept.reserve.flatMap(accept).forever
  28. } yield ()
  29. )
  30.  
  31. private def accept(reservation: Reservation[Any, Exception, AsynchronousSocketChannel]) =
  32. reservation.acquire.flatMap { socket =>
  33. socket.read(24, 30.seconds)
  34. .flatMap(chunk => putStrLn("Read chunk: " + chunk.mkString))
  35. .whenM(socket.isOpen)
  36. .forever
  37. .ensuring(reservation.release(Exit.Success(0)) *> putStrLn("Connection closed."))
  38. .catchAll(e => putStrLn("Connection closed due to: " + e.getMessage))
  39. .fork
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement