Created
June 17, 2019 17:35
-
-
Save jasonmartens/e2d0fd87edb97eb4eaccce071349a3ef to your computer and use it in GitHub Desktop.
Experimenting with ZIO & sockets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This program allows multiple connections to be created, but only the first connection is read from.