UNPKG

@woosh/meep-engine

Version:

Pure JavaScript game engine. Fully featured and production ready.

115 lines (87 loc) 2.64 kB
import { BinaryBuffer } from "../../core/binary/BinaryBuffer.js"; import { assert } from "../../core/assert.js"; /* packet header structure - TAG : 1 x utf8 string - ID : 1 x uint32 - PAYLOAD : N x bytes */ export class RemoteController { /** * * @type {WebSocket|null} */ #socket = null; #handlers = {}; #bound_event_handler = this.#handle_message_event.bind(this) /** * * @param {string} tag * @param {function(BinaryBuffer):Promise} handler * @param {*} thisArg */ addHandler(tag, handler, thisArg) { const existing = this.#handlers[tag]; if (existing !== undefined) { throw new Error(`Handler for tag '${tag}' already exists`); } this.#handlers[tag] = { method: handler, scope: thisArg }; } /** * NOTE: entire buffer contents will be sent up to current position * @param {string} tag * @param {BinaryBuffer} data */ send(tag, data) { assert.isString(tag, 'tag'); const buffer = new BinaryBuffer(); buffer.writeUTF8String(tag); buffer.writeBytes(data.raw_bytes, 0, data.position); buffer.trim(); this.#socket.send(buffer.data); } /** * * @param {MessageEvent} event * @private */ async #handle_message_event(event) { /** * @type {ArrayBuffer} */ const data = event.data; // console.log(`received message `, data); const buffer = BinaryBuffer.fromArrayBuffer(data); // read packet ID const packet_id = buffer.readUTF8String(); const handler = this.#handlers[packet_id]; if (handler === undefined) { console.error(`No handler for packet '${packet_id}'`); return; } try { await handler.method.call(handler.scope, buffer); } catch (e) { // console.error(`Failed to process remote call to '${packet_id}':`, e); } } /** * * @param {WebSocket} v */ set socket(v) { if (this.#socket !== null) { // TODO unbind socket } this.#socket = v; this.#socket.binaryType = "arraybuffer"; this.#socket.addEventListener('open', () => { console.log('socket connection open'); }); this.#socket.addEventListener('message', this.#bound_event_handler); } }