MWSE/frontend/Connection.ts

61 lines
1.6 KiB
TypeScript

interface IConnection{
endpoint: string;
autoPair?: boolean;
}
export default class Connection
{
public ws! : WebSocket;
public endpoint : URL;
public autoPair : boolean = false;
public connected : boolean = false;
constructor(options: IConnection){
this.endpoint = new URL(options.endpoint);
this.autoPair = options.autoPair || false;
this.connect();
}
public connect()
{
this.ws = new WebSocket(this.endpoint.href);
this.addWSEvents();
}
public addWSEvents()
{
this.ws.addEventListener("open", () => this.eventOpen());
this.ws.addEventListener("close", () => this.eventClose());
this.ws.addEventListener("error", () => this.eventError());
this.ws.addEventListener("message", ({data}) => this.eventMessage(data as string | ArrayBuffer));
}
private eventOpen()
{
this.connected = true;
}
private eventClose()
{
this.connected = false;
}
private eventError()
{
this.connected = false;
}
private recaivePackEvent : ((data:any) => any)[] = [];
public onRecaivePack(func:(data:any) => any)
{
this.recaivePackEvent.push(func);
}
private eventMessage(data: string | ArrayBuffer)
{
if(typeof data == "string")
{
for (const callback of this.recaivePackEvent) {
callback(JSON.parse(data));
}
}
}
public tranferToServer(data:any)
{
if(this.connected)
{
this.ws.send(JSON.stringify(data));
}
}
}