Remote web console.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conn.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. class Conn {
  2. constructor(id) {
  3. this.id = id;
  4. this.conn = null;
  5. this.pongTimeout = null;
  6. this.pongTime = 7500;
  7. this.q = [];
  8. this.onstatechange = () => {}
  9. this.onmessage = () => {};
  10. this.createConn();
  11. setInterval(() => this.send({ type: "ping" }), this.pongTime);
  12. this.gotPong();
  13. }
  14. createConn() {
  15. this.conn = new WebSocket(`${location.protocol.replace("http", "ws")}//${location.host}`);
  16. this.onstatechange("Connecting");
  17. this.connected = false;
  18. this.ready = false;
  19. this.conn.onclose = evt => {
  20. this.conn = null;
  21. this.onstatechange(`Closed: ${evt.code}`);
  22. setTimeout(this.createConn.bind(this), 2000);
  23. }
  24. this.conn.onopen = () => {
  25. this.onstatechange("Identifying");
  26. this.conn.send(JSON.stringify({ type: "identify-master", id: this.id }));
  27. this.q.forEach(el => this.conn.send(el));
  28. this.q = [];
  29. }
  30. this.conn.onmessage = msg => {
  31. console.log(msg.data);
  32. let obj = JSON.parse(msg.data);
  33. switch (obj.type) {
  34. case "identify-response":
  35. if (obj.err == null) {
  36. this.connected = true;
  37. this.onstatechange("Waiting for target");
  38. } else {
  39. this.onstatechange(`Error: ${obj.err}`);
  40. }
  41. break;
  42. case "target-connect":
  43. this.ready = true;
  44. this.onstatechange("Ready");
  45. break;
  46. case "target-disconnect":
  47. this.ready = false;
  48. this.onstatechange("Waiting for target");
  49. break;
  50. case "js-result":
  51. this.onjsresult(obj.err, obj.result);
  52. break;
  53. case "log":
  54. this.onlog(obj.log);
  55. break;
  56. case "pong":
  57. this.gotPong();
  58. break;
  59. default:
  60. console.warn("Unknown message type:", obj.type);
  61. }
  62. }
  63. }
  64. gotPong() {
  65. this.ready = true;
  66. this.onstatechange("Ready");
  67. if (this.pongTimeout)
  68. clearTimeout(this.pongTimeout);
  69. this.pongTimeout = setTimeout(() => {
  70. this.ready = false;
  71. this.onstatechange("Pong timeout");
  72. }, this.pongTime / 2);
  73. }
  74. runJavascript(js) {
  75. this.send({ type: "run-js", js });
  76. }
  77. send(obj) {
  78. if (this.connected)
  79. this.conn.send(JSON.stringify(obj));
  80. }
  81. }