chat-app/webpack/Client.ts

91 lines
2.0 KiB
TypeScript

import { EventEmitter } from 'events';
class Client extends EventEmitter {
uri: string;
ws: WebSocket | undefined;
started: boolean;
constructor (uri: string) {
super();
this.uri = uri;
this.started = false;
}
start() {
if (this.started == true) return;
this.started = true;
this.connect();
}
connect() {
if (!this.started) return;
this.ws = new WebSocket(this.uri);
this.ws.addEventListener('open', () => {
this.bindEventListeners();
this.sendArray([{
m: 'hi'
}]);
});
this.ws.addEventListener('close', evt => {
console.log('WebSocket disconnected');
if (this.started) {
setTimeout(() => {
this.emit('motd', 'Connecting...');
this.connect();
}, 1000);
} else {
this.ws = undefined;
this.emit('motd', 'Offline');
return;
}
});
}
stop() {
if (!this.started) return;
this.started = false;
this.ws.close();
this.ws.addEventListener('close', () => {
this.ws = undefined;
});
}
bindEventListeners() {
this.on('hi', msg => {
'motd' in msg ? this.emit('motd', msg.motd) : this.emit('motd', 'Connected');
});
this.ws.addEventListener('message', evt => {
if (!evt) return;
try {
let msgs = JSON.parse(evt.data);
for (let msg of msgs) {
if (!('m' in msg)) return;
this.emit(msg.m, msg);
}
} catch (err) {
console.error(err);
}
});
}
sendArray(arr) {
if (!this.started) return;
let jmsgs = JSON.stringify(arr);
this.ws.send(jmsgs);
}
}
export {
Client
}