UNPKG

@colyseus/ws-transport

Version:

```typescript import { Server } from "@colyseus/core"; import { WebSocketTransport } from "@colyseus/ws-transport";

127 lines (126 loc) 5.46 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var WebSocketTransport_exports = {}; __export(WebSocketTransport_exports, { WebSocketTransport: () => WebSocketTransport }); module.exports = __toCommonJS(WebSocketTransport_exports); var import_http = __toESM(require("http")); var import_url = require("url"); var import_ws = require("ws"); var import_core = require("@colyseus/core"); var import_WebSocketClient = require("./WebSocketClient.js"); function noop() { } function heartbeat() { this.pingCount = 0; } class WebSocketTransport extends import_core.Transport { constructor(options = {}) { super(); this._originalSend = null; if (options.maxPayload === void 0) { options.maxPayload = 4 * 1024; } if (options.perMessageDeflate === void 0) { options.perMessageDeflate = false; } this.pingIntervalMS = options.pingInterval !== void 0 ? options.pingInterval : 3e3; this.pingMaxRetries = options.pingMaxRetries !== void 0 ? options.pingMaxRetries : 2; if (!options.server && !options.noServer) { options.server = import_http.default.createServer(); } this.wss = new import_ws.WebSocketServer(options); this.wss.on("connection", this.onConnection); this.wss.on("error", (err) => (0, import_core.debugAndPrintError)(err)); this.server = options.server; if (this.pingIntervalMS > 0 && this.pingMaxRetries > 0) { this.server.on("listening", () => this.autoTerminateUnresponsiveClients(this.pingIntervalMS, this.pingMaxRetries)); this.server.on("close", () => clearInterval(this.pingInterval)); } } listen(port, hostname, backlog, listeningListener) { this.server.listen(port, hostname, backlog, listeningListener); return this; } shutdown() { this.wss.close(); this.server.close(); } simulateLatency(milliseconds) { if (this._originalSend == null) { this._originalSend = import_WebSocketClient.WebSocketClient.prototype.raw; } const originalSend = this._originalSend; import_WebSocketClient.WebSocketClient.prototype.raw = milliseconds <= Number.EPSILON ? originalSend : function(...args) { let [buf, ...rest] = args; buf = Array.from(buf); setTimeout(() => originalSend.apply(this, [buf, ...rest]), milliseconds); }; } autoTerminateUnresponsiveClients(pingInterval, pingMaxRetries) { this.pingInterval = setInterval(() => { this.wss.clients.forEach((client) => { if (client.pingCount >= pingMaxRetries) { (0, import_core.debugConnection)(`terminating unresponsive client`); return client.terminate(); } client.pingCount++; client.ping(noop); }); }, pingInterval); } async onConnection(rawClient, req) { rawClient.on("error", (err) => (0, import_core.debugAndPrintError)(err.message + "\n" + err.stack)); rawClient.on("pong", heartbeat); const parsedURL = new import_url.URL(`ws://server/${req.url}`); const sessionId = parsedURL.searchParams.get("sessionId"); const processAndRoomId = parsedURL.pathname.match(/\/[a-zA-Z0-9_\-]+\/([a-zA-Z0-9_\-]+)$/); const roomId = processAndRoomId && processAndRoomId[1]; const room = import_core.matchMaker.getLocalRoomById(roomId); rawClient.pingCount = 0; const client = new import_WebSocketClient.WebSocketClient(sessionId, rawClient); try { if (!room || !room.hasReservedSeat(sessionId, parsedURL.searchParams.get("reconnectionToken"))) { throw new Error("seat reservation expired."); } await room._onJoin(client, { headers: req.headers, token: parsedURL.searchParams.get("_authToken") ?? (0, import_core.getBearerToken)(req.headers.authorization), ip: req.headers["x-real-ip"] ?? req.headers["x-forwarded-for"] ?? req.socket.remoteAddress }); } catch (e) { (0, import_core.debugAndPrintError)(e); client.error(e.code, e.message, () => rawClient.close(import_core.Protocol.WS_CLOSE_WITH_ERROR)); } } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { WebSocketTransport });