33 lines
841 B
JavaScript
33 lines
841 B
JavaScript
import {SERVER_LATENCY} from '@/util/constants.js';
|
|
import EventEmitter from '@/util/event-emitter.js';
|
|
|
|
const textDecoder = new TextDecoder();
|
|
|
|
export default class Server {
|
|
constructor() {
|
|
this.emitter = new EventEmitter();
|
|
}
|
|
accept(connection, packet) {
|
|
this.emitter.invoke(packet.type, connection, packet.payload);
|
|
}
|
|
addPacketListener(type, listener) {
|
|
this.emitter.addListener(type, listener);
|
|
}
|
|
async readJson(path) {
|
|
return JSON.parse(textDecoder.decode(await this.readData(path)));
|
|
}
|
|
removePacketListener(type, listener) {
|
|
this.emitter.removeListener(type, listener);
|
|
}
|
|
send(connection, packet) {
|
|
if (SERVER_LATENCY > 0) {
|
|
setTimeout(() => {
|
|
this.transmit(connection, packet);
|
|
}, SERVER_LATENCY);
|
|
}
|
|
else {
|
|
this.transmit(connection, packet);
|
|
}
|
|
}
|
|
}
|