Last active
April 5, 2025 07:36
-
-
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/683088a38f2eb06c35a8f6a1f3b8dd729762121a
This file contains hidden or 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.6.4" | |
//> using dep "dev.zio::zio:2.1.16" | |
//> using dep "com.softwaremill.sttp.client3::zio:3.10.3" | |
// --------------------- | |
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