WebSocket上のJSON-RPCの結果を非同期で受け取るコード(typescript)
暇な時に解説書きます。
class JSONRPCWebSocket { private resultDic: { [key: number]: any; } = {}; private ws: WebSocket = null; private idCounter: number = 0; public interval: number = 100; public timeout: number = 3000; public closeWebSocket() { this.ws.close(); } /* 結果が戻ってきたら連想配列に格納する。 */ private onMessage = (args) => { var json = JSON.parse(args.data); console.log(this.interval); this.resultDic[json["id"]] = json["result"]; } /* 実行結果待ち */ private wait(id: number, time: number, resolve) { if (id in this.resultDic) { var result = this.resultDic[id]; delete this.resultDic[id]; resolve(result); } else if (time > this.timeout) { resolve("timeout"); } else { setTimeout(() => { this.wait(id, time + this.interval, resolve); }, this.interval); } } public openWebSocket(url : string) { this.ws = new WebSocket(url); //受信 this.ws.onmessage = this.onMessage; //接続成功時 this.ws.onopen = function (args) { console.log("open"); } this.ws.onclose = function (args) { console.log("close"); } this.ws.onerror = function (args) { console.log("error"); } } /* メソッドをJSON RPCの形にして投げて、結果を待つ。 */ public invoke(method: string, params: any[]): any { var id = this.idCounter++; var hash: { [key: number]: any; } = {}; hash["method"] = method; hash["params"] = params; hash["id"] = id; hash["type"] = "get"; var json = JSON.stringify(hash); this.ws.send(json); return new Promise((resolve, reject) => { this.wait(id, 0, resolve); }); } }