UNPKG

@colyseus/uwebsockets-transport

Version:

<div align="center"> <a href="https://github.com/colyseus/colyseus"> <img src="media/logo.svg?raw=true" width="60%" height="300" /> </a> <br> <br> <a href="https://npmjs.com/package/colyseus"> <img src="https://img.shields.io/npm/dm/coly

103 lines (102 loc) 2.61 kB
// packages/transport/uwebsockets-transport/src/uWebSocketClient.ts import EventEmitter from "events"; import "uWebSockets.js"; import { getMessageBytes, Protocol, ClientState, logger, debugMessage } from "@colyseus/core"; var uWebSocketWrapper = class extends EventEmitter { constructor(ws) { super(); this.ws = ws; } }; var ReadyState = { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 }; var uWebSocketClient = class { constructor(id, _ref) { this.state = ClientState.JOINING; this.readyState = ReadyState.OPEN; this._enqueuedMessages = []; this.id = this.sessionId = id; this._ref = _ref; _ref.on("close", () => this.readyState = ReadyState.CLOSED); } get ref() { return this._ref; } set ref(_ref) { this._ref = _ref; this.readyState = ReadyState.OPEN; } sendBytes(type, bytes, options) { debugMessage("send bytes(to %s): '%s' -> %j", this.sessionId, type, bytes); this.enqueueRaw( getMessageBytes.raw(Protocol.ROOM_DATA_BYTES, type, void 0, bytes), options ); } send(messageOrType, messageOrOptions, options) { debugMessage("send(to %s): '%s' -> %O", this.sessionId, messageOrType, messageOrOptions); this.enqueueRaw( getMessageBytes.raw(Protocol.ROOM_DATA, messageOrType, messageOrOptions), options ); } enqueueRaw(data, options) { if (options?.afterNextPatch) { this._afterNextPatchQueue.push([this, [data]]); return; } if (this.state !== ClientState.JOINED) { this._enqueuedMessages?.push(data); return; } this.raw(data, options); } raw(data, options, cb) { if (this.readyState !== ReadyState.OPEN) { return; } try { this._ref.ws.send(data, true, false); } catch (e) { this.readyState = ReadyState.CLOSED; } } error(code, message = "", cb) { this.raw(getMessageBytes[Protocol.ERROR](code, message)); if (cb) { process.nextTick(cb); } } leave(code, data) { if (this.readyState !== ReadyState.OPEN) { return; } this.readyState = ReadyState.CLOSING; if (code !== void 0) { this._ref.ws.end(code, data); } else { this._ref.ws.close(); } } close(code, data) { logger.warn("DEPRECATION WARNING: use client.leave() instead of client.close()"); try { throw new Error(); } catch (e) { logger.info(e.stack); } this.leave(code, data); } toJSON() { return { sessionId: this.sessionId, readyState: this.readyState }; } }; export { ReadyState, uWebSocketClient, uWebSocketWrapper };