Skip to content

Instantly share code, notes, and snippets.

@jasonmartens
Created June 17, 2019 17:35
Show Gist options
  • Save jasonmartens/e2d0fd87edb97eb4eaccce071349a3ef to your computer and use it in GitHub Desktop.
Save jasonmartens/e2d0fd87edb97eb4eaccce071349a3ef to your computer and use it in GitHub Desktop.
Experimenting with ZIO & sockets
import scalaz.nio._
import scalaz.nio.channels.{AsynchronousServerSocketChannel, AsynchronousSocketChannel}
import scalaz.zio.console._
import scalaz.zio.{App, ZIO}
object Bracket extends App {
override def run(args: List[String]): ZIO[Environment, Nothing, Int] = {
theSocket.foldM(
failure = err => putStrLn(s"Execution Failed with: $err") *> ZIO.succeed(1),
success = _ => ZIO.succeed(0)
)
}
val theSocket =
for {
address <- SocketAddress.inetSocketAddress("127.0.0.1", 1337)
socket <- AsynchronousServerSocketChannel()
_ <- socket.bind(address)
connections <- socket.accept.bracket(_.close.orDie)(doWork).forever.fork
worker <- connections.join
} yield worker
def doWork(work: AsynchronousSocketChannel): ZIO[Console, Exception, Unit] = {
val w = for {
chunk <- work.read(16)
str = chunk.toArray.map(_.toChar).mkString
_ <- putStrLn("content: " + str)
} yield ()
w.forever
}
}
@jasonmartens
Copy link
Author

This program allows multiple connections to be created, but only the first connection is read from.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment