43 lines
960 B
JavaScript
43 lines
960 B
JavaScript
import {SERVER_LATENCY} from '@/constants.js';
|
|
|
|
export default class Server {
|
|
constructor() {
|
|
this.listeners = {};
|
|
}
|
|
accept(connection, packet) {
|
|
const listeners = this.listeners[packet.type];
|
|
if (!listeners) {
|
|
return;
|
|
}
|
|
for (const i in listeners) {
|
|
listeners[i](connection, packet.payload);
|
|
}
|
|
}
|
|
addPacketListener(type, listener) {
|
|
if (!this.listeners[type]) {
|
|
this.listeners[type] = [];
|
|
}
|
|
this.listeners[type].push(listener);
|
|
}
|
|
removePacketListener(type, listener) {
|
|
const listeners = this.listeners[type];
|
|
if (!listeners) {
|
|
return;
|
|
}
|
|
const index = listeners.indexOf(listener);
|
|
if (-1 !== index) {
|
|
listeners.splice(index, 1);
|
|
}
|
|
}
|
|
send(connection, packet) {
|
|
if (SERVER_LATENCY > 0) {
|
|
setTimeout(() => {
|
|
this.transmit(connection, packet);
|
|
}, SERVER_LATENCY);
|
|
}
|
|
else {
|
|
this.transmit(connection, packet);
|
|
}
|
|
}
|
|
}
|