silphius/app/net/client.js
2024-08-07 14:29:05 -05:00

41 lines
1.0 KiB
JavaScript

import {CLIENT_LATENCY, CLIENT_PREDICTION} from '@/util/constants.js';
import EventEmitter from '@/util/event-emitter.js';
export default class Client {
emitter = new EventEmitter();
rtt = 0;
throughput = {$$down: 0, down: 0, $$up: 0, up: 0};
constructor() {
setInterval(() => {
const {throughput} = this;
throughput.down = throughput.$$down * 4;
throughput.up = throughput.$$up * 4;
throughput.$$down = throughput.$$up = 0;
}, 250);
}
accept(packet) {
if ('Heartbeat' === packet.type) {
this.rtt = packet.payload.rtt;
this.send(packet);
return;
}
this.emitter.invoke(packet.type, packet.payload);
}
addPacketListener(type, listener) {
this.emitter.addListener(type, listener);
}
removePacketListener(type, listener) {
this.emitter.removeListener(type, listener);
}
send(packet) {
if (CLIENT_LATENCY > 0 && !CLIENT_PREDICTION) {
setTimeout(() => {
this.transmit(packet);
}, CLIENT_LATENCY);
}
else {
this.transmit(packet);
}
}
}