소스 검색

state management

master
Martin Dørum 4 년 전
부모
커밋
2f864c9b12
2개의 변경된 파일31개의 추가작업 그리고 26개의 파일을 삭제
  1. 30
    25
      web/console/conn.js
  2. 1
    1
      web/console/index.html

+ 30
- 25
web/console/conn.js 파일 보기

@@ -2,8 +2,9 @@ class Conn {
constructor(id) {
this.id = id;
this.conn = null;
this.pongTimeout = null;
this.pongTime = 7500;
this.gotPong = false;
this.pongTime = 4000;
this.state = "idle";
this.q = [];

this.onstatechange = () => {}
@@ -11,24 +12,36 @@ class Conn {

this.createConn();

setInterval(() => this.send({ type: "ping" }), this.pongTime);
this.gotPong();
setInterval(() => {
if (this.state == "pong-timeout")
return;

if (!this.gotPong)
this.setState("pong-timeout");

this.send({ type: "ping" });
this.gotPong = false;
}, this.pongTime);
}

setState(state, msg) {
this.state = state;
this.onstatechange(msg || state);
}

createConn() {
this.conn = new WebSocket(`${location.protocol.replace("http", "ws")}//${location.host}`);
this.onstatechange("Connecting");
this.setState("connecting");
this.connected = false;
this.ready = false;

this.conn.onclose = evt => {
this.conn = null;
this.onstatechange(`Closed: ${evt.code}`);
this.setState("closed", `closed: ${evt.code}`);
setTimeout(this.createConn.bind(this), 2000);
}

this.conn.onopen = () => {
this.onstatechange("Identifying");
this.setState("identifying");
this.conn.send(JSON.stringify({ type: "identify-master", id: this.id }));

this.q.forEach(el => this.conn.send(el));
@@ -42,20 +55,18 @@ class Conn {
case "identify-response":
if (obj.err == null) {
this.connected = true;
this.onstatechange("Waiting for target");
this.setState("waiting-for-target");
} else {
this.onstatechange(`Error: ${obj.err}`);
this.setState("error", `error: ${obj.err}`);
}
break;

case "target-connect":
this.ready = true;
this.onstatechange("Ready");
this.setState("ready");
break;

case "target-disconnect":
this.ready = false;
this.onstatechange("Waiting for target");
this.setState("waiting-for-target")
break;

case "js-result":
@@ -67,7 +78,7 @@ class Conn {
break;

case "pong":
this.gotPong();
this.onPong();
break;

default:
@@ -76,16 +87,10 @@ class Conn {
}
}

gotPong() {
this.ready = true;
this.onstatechange("Ready");
if (this.pongTimeout)
clearTimeout(this.pongTimeout);

this.pongTimeout = setTimeout(() => {
this.ready = false;
this.onstatechange("Pong timeout");
}, this.pongTime / 2);
onPong() {
this.gotPong = true;
if (this.state == "pong-timeout")
this.setState("ready");
}

runJavascript(js) {

+ 1
- 1
web/console/index.html 파일 보기

@@ -6,7 +6,7 @@
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>State: <span id="state">Idle</span></div>
<div>State: <span id="state">idle</span></div>
<br>
<div>Insert this into your target site: <pre id="target-script"></pre></div>


Loading…
취소
저장