import zio.http._
import zio.http.Server
import zio.socket._
import zio._
import zio.duration._
import zio.stream.ZStream
object WebSocketAdvanced extends App {
private val open = Socket.succeed(WebSocketFrame.text("Greetings!"))
private val echo = Socket.collect[WebSocketFrame] { case WebSocketFrame.Text(text) =>
ZStream.repeat(WebSocketFrame.text(s"Received: $text")).schedule(Schedule.spaced(1 second)).take(3)
}
private val fooBar = Socket.collect[WebSocketFrame] {
case WebSocketFrame.Text("FOO") => ZStream.succeed(WebSocketFrame.text("BAR"))
case WebSocketFrame.Text("BAR") => ZStream.succeed(WebSocketFrame.text("FOO"))
}
private val protocol = SocketProtocol.subProtocol("json")
private val decoder = SocketDecoder.allowExtensions
private val socketApp = {
SocketApp(echo merge fooBar)
.onOpen(open)
.onClose(_ => console.putStrLn("Closed!").ignore)
.onError(_ => console.putStrLn("Error!").ignore)
.withDecoder(decoder)
.withProtocol(protocol)
}
private val app =
Http.collectZIO[Request] {
case Method.GET -> !! / "greet" / name => UIO(Response.text(s"Greetings ${name}!"))
case Method.GET -> !! / "subscriptions" => socketApp.toResponse
}
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
Server.start(8090, app).exitCode
}