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){
12 ws.addEventListener('message',function(ev){
13 that.queuedData.push(ev.data as ArrayBuffer)
14 if(that.onmsg!=null)that.onmsg();
17 public async waitNewMessage(){
18 return new Promise((resolve)=>{
25 public availableBytes(){
27 let len=this.queuedData.length
28 for(let i1=0;i1<len;i1++){
29 sumBytes+=this.queuedData[i1].byteLength;
33 public async read(size: number): Promise<ArrayBuffer> {
35 let datar=new Uint8Array(new ArrayBuffer(size));
37 if(this.ws.readyState!=WebSocket.OPEN){
38 throw new RpcExtendError('WebSocket EOF')
40 let data1=this.queuedData.shift()
42 await this.waitNewMessage();
45 if(data1.byteLength<=remain){
46 datar.set(new Uint8Array(data1),size-remain);
47 remain-=data1.byteLength;
49 datar.set(new Uint8Array(data1,0,remain),size-remain)
50 data1=data1.slice(remain)
51 this.queuedData.unshift(data1)
57 public async write(data: ArrayBufferLike): Promise<void> {
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!));
75 public async wrapWebSocket(ws:WebSocket){
77 this.ws!.binaryType='arraybuffer';
80 await this.client!.run()