Last active
February 3, 2026 20:26
-
-
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/7d586c9f1a69eb35208060db135c46aa25142321
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 License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // 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.7.4" | |
| //> using dep "dev.zio::zio:2.1.23" | |
| //> using dep "com.softwaremill.sttp.client3::zio:3.11.0" | |
| // --------------------- | |
| 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