@colyseus/ws-transport
Version:
```typescript import { Server } from "@colyseus/core"; import { WebSocketTransport } from "@colyseus/ws-transport";
73 lines (72 loc) • 1.9 kB
JavaScript
// packages/transport/ws-transport/src/WebSocketClient.ts
import "ws";
import {
Protocol,
ClientState,
getMessageBytes,
logger,
debugMessage
} from "@colyseus/core";
var SEND_OPTS = { binary: true };
var WebSocketClient = class {
constructor(id, ref) {
this.state = ClientState.JOINING;
this._enqueuedMessages = [];
this._numMessagesLastSecond = 0;
this._lastMessageTime = 0;
this.sessionId = this.id = id;
this.ref = ref;
}
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' -> %j", 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) {
this.ref.send(data, SEND_OPTS, cb);
}
error(code, message = "", cb) {
this.raw(getMessageBytes[Protocol.ERROR](code, message), void 0, cb);
}
get readyState() {
return this.ref.readyState;
}
leave(code, data) {
this.ref.close(code, data);
}
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 {
WebSocketClient
};