|
| 1 | +# WebSocket Client |
| 2 | + |
| 3 | +The [`WebSocketClient`](https://www.javadoc.io/doc/org.http4s/http4s-dom_sjs1_2.13/latest/org/http4s/dom/WSClient$.html) creates a standard http4s [`WSClientHighLevel`](https://http4s.org/v0.23/api/org/http4s/client/client). |
| 4 | + |
| 5 | +## Example |
| 6 | + |
| 7 | +```scala mdoc:js |
| 8 | +<div> |
| 9 | + <h3>Send Text Frame</h3> |
| 10 | + <input id="message" size="64" type="text"> |
| 11 | + <button id="button">Send</button> |
| 12 | +</div> |
| 13 | +<div style="display: flex"> |
| 14 | + <div style="flex: 50%"> |
| 15 | + <h3>Sent</h3> |
| 16 | + <div id="sent" style="width: 100%"></div> |
| 17 | + </div> |
| 18 | + <div style="flex: 50%"> |
| 19 | + <h3>Received</h3> |
| 20 | + <div id="received" style="width: 100%"></div> |
| 21 | + </div> |
| 22 | +</div> |
| 23 | +--- |
| 24 | +import cats.effect._ |
| 25 | +import cats.effect.unsafe.implicits._ |
| 26 | +import org.http4s.client.websocket._ |
| 27 | +import org.http4s.dom._ |
| 28 | +import org.http4s.syntax.all._ |
| 29 | +import org.scalajs.dom._ |
| 30 | + |
| 31 | +val message = document.getElementById("message").asInstanceOf[html.Input] |
| 32 | +val button = document.getElementById("button").asInstanceOf[html.Button] |
| 33 | +val sent = document.getElementById("sent").asInstanceOf[html.Element] |
| 34 | +val received = document.getElementById("received").asInstanceOf[html.Element] |
| 35 | + |
| 36 | +val request = WSRequest(uri"wss://ws.postman-echo.com/raw") |
| 37 | +val app = WebSocketClient[IO].connectHighLevel(request).use { conn => |
| 38 | + |
| 39 | + def log(e: html.Element, text: String): IO[Unit] = |
| 40 | + IO { |
| 41 | + val p = document.createElement("p") |
| 42 | + p.innerHTML = text |
| 43 | + e.appendChild(p) |
| 44 | + () |
| 45 | + } |
| 46 | + |
| 47 | + val sendMessage: IO[Unit] = for { |
| 48 | + text <- IO(message.value) |
| 49 | + frame = WSFrame.Text(text) |
| 50 | + _ <- conn.send(frame) |
| 51 | + _ <- log(sent, frame.toString) |
| 52 | + } yield () |
| 53 | + |
| 54 | + val receiveMessages: IO[Unit] = |
| 55 | + conn.receiveStream |
| 56 | + .evalTap(frame => log(received, frame.toString)) |
| 57 | + .compile |
| 58 | + .drain |
| 59 | + |
| 60 | + val logCloseFrame: IO[Unit] = |
| 61 | + conn.closeFrame.get.flatMap(frame => log(received, frame.toString)) |
| 62 | + |
| 63 | + val registerOnClick = IO(button.onclick = _ => sendMessage.unsafeRunAndForget()) |
| 64 | + val deregisterOnClick = IO(button.onclick = null) |
| 65 | + |
| 66 | + registerOnClick *> receiveMessages *> logCloseFrame *> deregisterOnClick |
| 67 | +} |
| 68 | + |
| 69 | +app.unsafeRunAndForget() |
| 70 | +``` |
0 commit comments