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){
10 ws.addEventListener('message',function(ev){
11 that.queuedData.push(ev.data as ArrayBuffer)
12 if(that.onmsg!=null)that.onmsg();
15 public async waitNewMessage(){
16 return new Promise((resolve)=>{
23 async read(size: number): Promise<ArrayBuffer> {
25 let datar=new Uint8Array(new ArrayBuffer(size));
27 let data1=this.queuedData.shift()
29 await this.waitNewMessage();
32 if(data1.byteLength<=remain){
33 datar.set(new Uint8Array(data1),size-remain);
34 remain-=data1.byteLength;
36 datar.set(new Uint8Array(data1,0,remain),size-remain)
37 data1=data1.slice(remain)
38 this.queuedData.unshift(data1)
44 async write(data: ArrayBufferLike): Promise<void> {
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!));
62 public async wrapWebSocket(ws:WebSocket){
64 this.ws!.binaryType='arraybuffer';
67 await this.client!.run()