76 lines
1.9 KiB
TypeScript
76 lines
1.9 KiB
TypeScript
export interface IConnection{
|
|
endpoint: string;
|
|
}
|
|
export 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);
|
|
}
|
|
public connect()
|
|
{
|
|
this.ws = new WebSocket(this.endpoint.href);
|
|
this.addWSEvents();
|
|
}
|
|
public disconnect()
|
|
{
|
|
this.ws.close();
|
|
}
|
|
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;
|
|
for (const callback of this.activeConnectionEvent) {
|
|
callback(void 0);
|
|
}
|
|
}
|
|
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 activeConnectionEvent : Function[] = [];
|
|
public onActive(func:Function)
|
|
{
|
|
if(this.connected)
|
|
{
|
|
func()
|
|
}else{
|
|
this.activeConnectionEvent.push(func);
|
|
}
|
|
}
|
|
private eventMessage(data: string | ArrayBuffer)
|
|
{
|
|
if(typeof data == "string")
|
|
{
|
|
let $data = JSON.parse(data);
|
|
for (const callback of this.recaivePackEvent) {
|
|
callback($data);
|
|
}
|
|
}
|
|
}
|
|
public tranferToServer(data:any)
|
|
{
|
|
if(this.connected)
|
|
{
|
|
this.ws.send(JSON.stringify(data));
|
|
}
|
|
}
|
|
} |