Skip to content

Instantly share code, notes, and snippets.

@adamw
Last active October 15, 2019 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamw/ab576f290ce18a5f1a620c185d95b41c to your computer and use it in GitHub Desktop.
Save adamw/ab576f290ce18a5f1a620c185d95b41c to your computer and use it in GitHub Desktop.
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