Last active
May 25, 2024 10:20
-
-
Save dacr/f68ba493dd77859b8f3b0add519cf668 to your computer and use it in GitHub Desktop.
Simple websocket example / published by https://github.com/dacr/code-examples-manager #5642b2ef-3f21-4a10-8924-f435bb69306d/8aa2eec3af0a78f8dda376cb5761e92bf6588d02
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
// summary : Simple websocket example | |
// keywords : scala, zio, sttp, websocket | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 5642b2ef-3f21-4a10-8924-f435bb69306d | |
// created-on : 2022-12-30T09:25:55+01:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "dev.zio::zio:2.0.6" | |
//> using dep "com.softwaremill.sttp.client3::zio:3.8.8" | |
// --------------------- | |
import zio.* | |
import sttp.client3.*, sttp.client3.basicRequest.*, sttp.ws.*, sttp.model.* | |
object WebSocketCat extends ZIOAppDefault { | |
val defaultTarget = "wss://ws.postman-echo.com/raw" // This is an echo service also | |
// val defaultTarget = "ws://127.0.0.1:3000/ws/test/echo" | |
//val defaultTarget = "ws://127.0.0.1:3000/ws/test/stream" | |
def processWebsocket(ws: WebSocket[Task]): Task[Unit] = { | |
val receiveOne = ws.receiveText().flatMap(res => Console.printLine(s"$res")) | |
val sendOne = Console.readLine.flatMap(line => ws.sendText(line)) | |
receiveOne.forever.race(sendOne.forever) | |
} | |
def run = | |
for { | |
args <- getArgs | |
target = args.headOption.getOrElse(defaultTarget) | |
targetURI <- ZIO.fromEither(Uri.parse(target)) | |
backend <- sttp.client3.httpclient.zio.HttpClientZioBackend() | |
response <- basicRequest | |
.get(targetURI) | |
.response(asWebSocket(processWebsocket)) | |
.send(backend) | |
} yield response | |
} | |
WebSocketCat.main(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment