Last active
October 15, 2019 16:25
-
-
Save adamw/ab576f290ce18a5f1a620c185d95b41c to your computer and use it in GitHub Desktop.
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
import cats.effect.{ContextShift, IO, Timer} | |
import org.asynchttpclient.ws.{WebSocket, WebSocketListener} | |
import sttp.client._ | |
import sttp.client.asynchttpclient.WebSocketHandler | |
import sttp.client.ws.WebSocketResponse | |
import scala.concurrent.ExecutionContext.global | |
import scala.concurrent.duration._ | |
object CatsWebsocketExample extends App { | |
// setting up cats-effect | |
implicit val cs: ContextShift[IO] = IO.contextShift(global) | |
implicit val timer: Timer[IO] = IO.timer(global) | |
AsyncHttpClientCatsBackend[IO]() | |
.flatMap { implicit backend => | |
// creating a listener, which will print all incoming messages to the console | |
val listener = new WebSocketListener { | |
override def onOpen(ws: WebSocket): Unit = {} | |
override def onClose(ws: WebSocket, code: Int, reason: String): Unit = {} | |
override def onError(t: Throwable): Unit = {} | |
override def onTextFrame(payload: String, final: Boolean, rsv: Int): Unit = { | |
println(s"RECEIVED: $payload") | |
} | |
} | |
// using a test websocket endpoint | |
val response: IO[WebSocketResponse[WebSocket]] = basicRequest | |
.get(uri"wss://echo.websocket.org") | |
.openWebsocket(WebSocketHandler.fromListener(listener)) | |
// the "response" is an effect once which will store the AHC websocket instance, | |
// once the websocket is established | |
response.flatMap { r => | |
println("Websocket established!") | |
// describing a process, which sleeps for one second, sends a message, and | |
// then recursively calls itself. The message-sending is a side-effecting | |
// operation wrapped with IO. Error handling is missing. | |
def send: IO[Unit] = | |
IO.sleep(1.second) | |
.flatMap(_ => IO(r.result.sendTextFrame("Hello!"))) | |
.flatMap(_ => send) | |
send | |
} | |
} | |
.unsafeRunSync() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment