@colyseus/ws-transport
Version:
```typescript import { Server } from "@colyseus/core"; import { WebSocketTransport } from "@colyseus/ws-transport";
150 lines (149 loc) • 5.88 kB
JavaScript
// packages/transport/ws-transport/src/WebSocketTransport.ts
import http from "http";
import { URL } from "url";
import { WebSocketServer } from "ws";
import express from "express";
import { matchMaker, Protocol, Transport, debugAndPrintError, debugConnection, getBearerToken, CloseCode, connectClientToRoom, isDevMode } from "@colyseus/core";
import { WebSocketClient } from "./WebSocketClient.mjs";
function noop() {
}
function heartbeat() {
this.pingCount = 0;
}
var WebSocketTransport = class extends Transport {
constructor(options = {}) {
super();
// False when sharing an external HTTP server, such as Vite's dev server.
this.shouldShutdownServer = true;
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 = http.createServer();
}
this.wss = new WebSocketServer(options);
this.wss.on("connection", this.onConnection);
this.wss.on("error", (err) => debugAndPrintError(err));
this.server = options.server;
if (this.server && this.pingIntervalMS > 0 && this.pingMaxRetries > 0) {
this.server.on("listening", () => this.autoTerminateUnresponsiveClients(this.pingIntervalMS, this.pingMaxRetries));
this.server.on("close", () => clearInterval(this.pingInterval));
}
}
getExpressApp() {
if (!this.server) {
throw new Error("WebSocketTransport is not attached to an HTTP server.");
}
if (!this._expressApp) {
this._expressApp = express();
this.server.on("request", this._expressApp);
}
return this._expressApp;
}
listen(port, hostname, backlog, listeningListener) {
if (!this.server) {
throw new Error("WebSocketTransport is not attached to an HTTP server.");
}
this.server.listen(port, hostname, backlog, listeningListener);
return this;
}
/**
* Attach this transport to an already-running HTTP server.
*
* `colyseus/vite` uses this in dev mode so Colyseus can reuse Vite's HTTP server
* instead of creating and owning a separate one.
*/
attachToServer(server, options = {}) {
this.server = server;
this.shouldShutdownServer = false;
server.on("upgrade", (req, socket, head) => {
if (options.filter && !options.filter(req)) {
return;
}
this.wss.handleUpgrade(req, socket, head, (ws) => {
this.wss.emit("connection", ws, req);
});
});
if (this.pingIntervalMS > 0 && this.pingMaxRetries > 0 && !this.pingInterval) {
this.autoTerminateUnresponsiveClients(this.pingIntervalMS, this.pingMaxRetries);
server.on("close", () => clearInterval(this.pingInterval));
}
return this;
}
/**
* Close the websocket server and all active websocket connections.
*
* When attached through `attachToServer()`, keep the shared HTTP server alive.
* This is required for `colyseus/vite`, which does not own the Vite dev server.
*/
shutdown() {
this.wss.close();
if (this.shouldShutdownServer) {
this.server?.close();
}
}
simulateLatency(milliseconds) {
if (this._originalSend == null) {
this._originalSend = WebSocketClient.prototype.raw;
}
const originalSend = this._originalSend;
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) {
debugConnection(`terminating unresponsive client`);
return client.terminate();
}
client.pingCount++;
client.ping(noop);
});
}, pingInterval);
}
async onConnection(rawClient, req) {
rawClient.on("error", (err) => debugAndPrintError(err.message + "\n" + err.stack));
rawClient.on("pong", heartbeat);
rawClient.pingCount = 0;
const parsedURL = new 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];
if (!sessionId && !roomId) {
const timeout = setTimeout(() => rawClient.close(CloseCode.NORMAL_CLOSURE), 1e3);
rawClient.on("message", (_) => rawClient.send(new Uint8Array([Protocol.PING])));
rawClient.on("close", () => clearTimeout(timeout));
return;
}
const room = matchMaker.getLocalRoomById(roomId);
const client = new WebSocketClient(sessionId, rawClient);
const reconnectionToken = parsedURL.searchParams.get("reconnectionToken");
const skipHandshake = parsedURL.searchParams.has("skipHandshake");
try {
await connectClientToRoom(room, client, {
headers: new Headers(req.headers),
token: parsedURL.searchParams.get("_authToken") ?? getBearerToken(req.headers.authorization),
ip: req.headers["x-real-ip"] ?? req.headers["x-forwarded-for"] ?? req.socket.remoteAddress
}, {
reconnectionToken,
skipHandshake
});
} catch (e) {
debugAndPrintError(e);
client.error(e.code, e.message, () => rawClient.close(reconnectionToken ? isDevMode ? CloseCode.MAY_TRY_RECONNECT : CloseCode.FAILED_TO_RECONNECT : CloseCode.WITH_ERROR));
}
}
};
export {
WebSocketTransport
};