40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
export default class PersistentWebsocket {
|
|
private webSocket?: WebSocket;
|
|
|
|
public constructor(
|
|
protected readonly url: string,
|
|
private readonly handler: MessageHandler,
|
|
protected readonly reconnectOnClose: boolean = true,
|
|
) {
|
|
}
|
|
|
|
public run() {
|
|
this.webSocket = new WebSocket(this.url);
|
|
this.webSocket.addEventListener('open', (e) => {
|
|
console.debug('Websocket connected');
|
|
});
|
|
this.webSocket.addEventListener('message', (e) => {
|
|
this.handler(this.webSocket!, e);
|
|
});
|
|
this.webSocket.addEventListener('error', (e) => {
|
|
console.error('Websocket error', e);
|
|
});
|
|
this.webSocket.addEventListener('close', (e) => {
|
|
this.webSocket = undefined;
|
|
console.debug('Websocket closed', e.code, e.reason);
|
|
|
|
if (this.reconnectOnClose) {
|
|
setTimeout(() => this.run(), 1000);
|
|
}
|
|
});
|
|
}
|
|
|
|
public send(data: string) {
|
|
if (!this.webSocket) throw new Error('WebSocket not connected');
|
|
|
|
this.webSocket.send(data);
|
|
}
|
|
}
|
|
|
|
export type MessageHandler = (webSocket: WebSocket, e: MessageEvent) => void;
|