Correctly handle socket state in the app and make it possible to listen for events
This commit is contained in:
parent
f0ca8bc3a3
commit
c8d89e0964
6 changed files with 89 additions and 16 deletions
53
resources/scripts/plugins/Websocket.ts
Normal file
53
resources/scripts/plugins/Websocket.ts
Normal file
|
@ -0,0 +1,53 @@
|
|||
import Sockette from 'sockette';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
export const SOCKET_EVENTS = [
|
||||
'SOCKET_OPEN',
|
||||
'SOCKET_RECONNECT',
|
||||
'SOCKET_CLOSE',
|
||||
'SOCKET_ERROR',
|
||||
];
|
||||
|
||||
export class Websocket extends EventEmitter {
|
||||
socket: Sockette;
|
||||
|
||||
constructor (url: string, protocol: string) {
|
||||
super();
|
||||
|
||||
this.socket = new Sockette(url, {
|
||||
protocols: protocol,
|
||||
onmessage: e => {
|
||||
try {
|
||||
let { event, args } = JSON.parse(e.data);
|
||||
this.emit(event, ...args);
|
||||
} catch (ex) {
|
||||
console.warn('Failed to parse incoming websocket message.', ex);
|
||||
}
|
||||
},
|
||||
onopen: () => this.emit('SOCKET_OPEN'),
|
||||
onreconnect: () => this.emit('SOCKET_RECONNECT'),
|
||||
onclose: () => this.emit('SOCKET_CLOSE'),
|
||||
onerror: () => this.emit('SOCKET_ERROR'),
|
||||
});
|
||||
}
|
||||
|
||||
close (code?: number, reason?: string) {
|
||||
this.socket.close(code, reason);
|
||||
}
|
||||
|
||||
open () {
|
||||
this.socket.open();
|
||||
}
|
||||
|
||||
json (data: any) {
|
||||
this.socket.json(data);
|
||||
}
|
||||
|
||||
reconnect () {
|
||||
this.socket.reconnect();
|
||||
}
|
||||
|
||||
send (data: any) {
|
||||
this.socket.send(data);
|
||||
}
|
||||
}
|
Reference in a new issue