update c build script
[PxpRpc.git] / typescript / pxprpc / backend.ts
blob5e143d4086ad202453bceea006e12ca9ee03fb8b
2 import { Client, Io } from "./base";
3 import { RpcExtendError } from "./extend";
7 export class WebSocketIo implements Io{
8     public queuedData:Array<ArrayBufferLike>=new Array();
9     protected onmsg:null|(()=>void)=null;
10     public constructor(public ws:WebSocket){
11         var that=this;
12         ws.addEventListener('message',function(ev){
13             that.queuedData.push(ev.data as ArrayBuffer)
14             if(that.onmsg!=null)that.onmsg();
15         });
16     };
17     public async waitNewMessage(){
18         return new Promise((resolve)=>{
19             this.onmsg=()=>{
20                 this.onmsg=null;
21                 resolve(null);
22             }
23         });
24     }
25     public availableBytes(){
26         let sumBytes=0;
27         let len=this.queuedData.length
28         for(let i1=0;i1<len;i1++){
29             sumBytes+=this.queuedData[i1].byteLength;
30         }
31         return sumBytes;
32     }
33     public async read(size: number): Promise<ArrayBuffer> {
34         let remain=size;
35         let datar=new Uint8Array(new ArrayBuffer(size));
36         while(remain>0){
37             if(this.ws.readyState!=WebSocket.OPEN){
38                 throw new RpcExtendError('WebSocket EOF')
39             }
40             let data1=this.queuedData.shift()
41             if(data1==undefined){
42                 await this.waitNewMessage();
43                 continue;
44             }
45             if(data1.byteLength<=remain){
46                 datar.set(new Uint8Array(data1),size-remain);
47                 remain-=data1.byteLength;
48             }else{
49                 datar.set(new Uint8Array(data1,0,remain),size-remain)
50                 data1=data1.slice(remain)
51                 this.queuedData.unshift(data1)
52                 remain=0;
53             }
54         }
55         return datar.buffer;
56     }
57     public async write(data: ArrayBufferLike): Promise<void> {
58         this.ws.send(data);
59     }
62 export class PxprpcWebSocketClient{
63     protected ws:WebSocket|undefined
64     protected client?:Client
65     public async connect(url:string){
66         this.ws=new WebSocket(url);
67         this.ws!.binaryType='arraybuffer';
68         return new Promise((resolve)=>{
69             this.ws!.addEventListener('open',(ev)=>{
70                 this.client=new Client(new WebSocketIo(this.ws!));
71                 resolve(null);
72             });
73         });
74     }
75     public async wrapWebSocket(ws:WebSocket){
76         this.ws=ws;
77         this.ws!.binaryType='arraybuffer';
78     }
79     public async run(){
80         await this.client!.run()
81     }
82     public async close(){
83         this.client!.close()
84     }
85     public rpc(){
86         return this.client;
87     }