example.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. var head = 0, tail = 0, ring = new Array();
  2. function get_appropriate_ws_url(extra_url)
  3. {
  4. var pcol;
  5. var u = document.URL;
  6. /*
  7. * We open the websocket encrypted if this page came on an
  8. * https:// url itself, otherwise unencrypted
  9. */
  10. if (u.substring(0, 5) === "https") {
  11. pcol = "wss://";
  12. u = u.substr(8);
  13. } else {
  14. pcol = "ws://";
  15. if (u.substring(0, 4) === "http")
  16. u = u.substr(7);
  17. }
  18. u = u.split("/");
  19. /* + "/xxx" bit is for IE10 workaround */
  20. return pcol + u[0] + "/" + extra_url;
  21. }
  22. function new_ws(urlpath, protocol)
  23. {
  24. return new WebSocket(urlpath, protocol);
  25. }
  26. document.addEventListener("DOMContentLoaded", function() {
  27. var ws = new_ws(get_appropriate_ws_url(""), "lws-minimal-proxy");
  28. try {
  29. ws.onopen = function() {
  30. document.getElementById("r").disabled = 0;
  31. };
  32. ws.onmessage =function got_packet(msg) {
  33. var n, s = "";
  34. ring[head] = msg.data + "\n";
  35. head = (head + 1) % 20;
  36. if (tail === head)
  37. tail = (tail + 1) % 20;
  38. n = tail;
  39. do {
  40. s = s + ring[n];
  41. n = (n + 1) % 20;
  42. } while (n !== head);
  43. document.getElementById("r").value = s;
  44. document.getElementById("r").scrollTop =
  45. document.getElementById("r").scrollHeight;
  46. };
  47. ws.onclose = function(){
  48. document.getElementById("r").disabled = 1;
  49. };
  50. } catch(exception) {
  51. alert("<p>Error " + exception);
  52. }
  53. }, false);