|
| 1 | +import { Player } from '../world/actor/player/player'; |
| 2 | +import { logger } from '@runejs/logger'; |
| 3 | +import { getFiles } from '../util/files'; |
| 4 | +import { ByteBuffer } from '@runejs/byte-buffer'; |
| 5 | + |
| 6 | +interface InboundPacket { |
| 7 | + opcode: number; |
| 8 | + size: number; |
| 9 | + handler: (player: Player, packet: { packetId: number, packetSize: number, buffer: ByteBuffer }) => void; |
| 10 | +} |
| 11 | + |
| 12 | +export const incomingPackets = new Map<number, InboundPacket>(); |
| 13 | + |
| 14 | +export const PACKET_DIRECTORY = './dist/net/inbound-packets'; |
| 15 | + |
| 16 | +export async function loadPackets(): Promise<Map<number, InboundPacket>> { |
| 17 | + incomingPackets.clear(); |
| 18 | + |
| 19 | + for await(const path of getFiles(PACKET_DIRECTORY, [ '.' ])) { |
| 20 | + const location = './inbound-packets' + path.substring(PACKET_DIRECTORY.length).replace('.js', ''); |
| 21 | + const packet = require(location).default; |
| 22 | + if(Array.isArray(packet)) { |
| 23 | + packet.forEach(p => incomingPackets.set(p.opcode, p)); |
| 24 | + } else { |
| 25 | + incomingPackets.set(packet.opcode, packet); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return incomingPackets; |
| 30 | +} |
| 31 | + |
| 32 | +export function handlePacket(player: Player, packetId: number, packetSize: number, buffer: ByteBuffer): void { |
| 33 | + const incomingPacket = incomingPackets.get(packetId); |
| 34 | + |
| 35 | + if(!incomingPacket) { |
| 36 | + logger.info(`Unknown packet ${packetId} with size ${packetSize} received.`); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + new Promise(resolve => { |
| 41 | + incomingPacket.handler(player, { packetId, packetSize, buffer }); |
| 42 | + resolve(); |
| 43 | + }).catch(error => logger.error(`Error handling inbound packet: ${error}`)); |
| 44 | +} |
0 commit comments