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

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