Skip to content

Instantly share code, notes, and snippets.

@zetashift
Created March 11, 2023 20:43
Show Gist options
  • Save zetashift/3ef8e8da6e24f507b36eebf016c566b2 to your computer and use it in GitHub Desktop.
Save zetashift/3ef8e8da6e24f507b36eebf016c566b2 to your computer and use it in GitHub Desktop.
Websocket Scala

Using Websockets

def sendInput(input: html.Input, socket: WebSocket) = {
  input.onkeyup = (e: Event) => socket.send(input.value)
}

def echoWebSocket(input: html.Input, pre: html.Pre) = {
  val echo = "ws://echo.websocket.events"

  val socket = new WebSocket(echo)
  socket.onmessage = {
    (e: MessageEvent) =>
      pre.textContent += e.data.toString
  }

  socket.onopen = (e: Event) => sendInput(input, socket)
}
<pre id="demo6-output"></pre>
<input id="demo6-input" type="text" />
<button id="demo6-btn">Run</button>
---
val input = document.getElementById("demo6-input").asInstanceOf[html.Input]
val output = document.getElementById("demo6-output").asInstanceOf[html.Pre]
document.getElementById("demo6-btn").addEventListener("click", (ev: Event) => {
  echoWebSocket(input, output)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment