<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
  var wsUri = "ws://127.0.0.1:1234";
  var output;

  function init() {
    output = document.getElementById("output");
    websocket = new WebSocket(wsUri);
    websocket.binaryType = "arraybuffer";
    websocket.onopen = function (evt) {
      onOpen(evt);
    };
    websocket.onclose = function (evt) {
      onClose(evt);
    };
    websocket.onmessage = function (evt) {
      onMessage(evt);
    };
    websocket.onerror = function (evt) {
      onError(evt);
    };
  }
  function toMessage(source) {
    const array = new Uint8Array(source.length);
    source.forEach((element, index) => {
      array[index] =
        typeof element === "string" ? element.charCodeAt(0) : element;
    });
    return array;
  }

  function onOpen(evt) {
    writeToScreen("sent message /foo int: 123");
    websocket.send(
      toMessage(["/", "f", "o", "o", 0, 0, 0, 0, ",", "i", 0, 0, 0, 0, 0, 123])
    );
  }

  function onClose(evt) {
    writeToScreen("DISCONNECTED");
  }

  function onMessage(evt) {
    const array = new Uint8Array(evt.data);
    let str = "";
    array.forEach((element, index) => {
      if (element >= 32 && element <= 126) {
        str += String.fromCharCode(element);
      } else {
        str += " ";
      }
    });
    writeToScreen('<span style="color: blue;">RESPONSE: ' + str + "</span>");
    websocket.close();
  }

  function onError(evt) {
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
  }

  function doSend(message) {}

  function writeToScreen(message) {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
  }

  window.addEventListener("load", init, false);
</script>

<h2>WebSocket client test</h2>

<div id="output"></div>
