typescript backend
[PxpRpc.git] / typescript / pxprpc / backend.ts
blob10305b9d83bc03d6c349a04ef2bc4c5a8cbb63a7
1 import { Client, Io } from "./base";
5 export class WebSocketIo implements Io{
6     public queuedData:Array<ArrayBufferLike>=new Array();
7     protected onmsg:null|(()=>void)=null;
8     public constructor(public ws:WebSocket){
9         var that=this;
10         ws.addEventListener('message',function(ev){
11             that.queuedData.push(ev.data as ArrayBuffer)
12             if(that.onmsg!=null)that.onmsg();
13         });
14     };
15     public async waitNewMessage(){
16         return new Promise((resolve)=>{
17             this.onmsg=()=>{
18                 this.onmsg=null;
19                 resolve(null);
20             }
21         });
22     }
23     async read(size: number): Promise<ArrayBuffer> {
24         let remain=size;
25         let datar=new Uint8Array(new ArrayBuffer(size));
26         while(remain>0){
27             let data1=this.queuedData.shift()
28             if(data1==undefined){
29                 await this.waitNewMessage();
30                 continue;
31             }
32             if(data1.byteLength<=remain){
33                 datar.set(new Uint8Array(data1),size-remain);
34                 remain-=data1.byteLength;
35             }else{
36                 datar.set(new Uint8Array(data1,0,remain),size-remain)
37                 data1=data1.slice(remain)
38                 this.queuedData.unshift(data1)
39                 remain=0;
40             }
41         }
42         return datar.buffer;
43     }
44     async write(data: ArrayBufferLike): Promise<void> {
45         this.ws.send(data);
46     }
49 export class PxprpcWebSocketClient{
50     protected ws:WebSocket|undefined
51     protected client?:Client
52     public async connect(url:string){
53         this.ws=new WebSocket(url);
54         this.ws!.binaryType='arraybuffer';
55         return new Promise((resolve)=>{
56             this.ws!.addEventListener('open',(ev)=>{
57                 this.client=new Client(new WebSocketIo(this.ws!));
58                 resolve(null);
59             });
60         });
61     }
62     public async wrapWebSocket(ws:WebSocket){
63         this.ws=ws;
64         this.ws!.binaryType='arraybuffer';
65     }
66     public async run(){
67         await this.client!.run()
68     }
69     public async close(){
70         this.client!.close()
71     }
72     public rpc(){
73         return this.client;
74     }