This commit is contained in:
azw 2023-08-15 21:16:22 +08:00
parent e2f2442aa1
commit 3b78707f0d

View File

@ -56,20 +56,20 @@ class ClientNet {
async connect() { async connect() {
this.conn = await ws.connect(this.url); this.conn = await ws.connect(this.url);
this.on('binary', this.#onReceive.bind(this)); this.on('binary', this.onReceive.bind(this));
} }
on(eventName, ...args) { on(eventName, ...args) {
this.conn.on(eventName, ...args); this.conn.on(eventName, ...args);
} }
async #onReceive(inStream) { async onReceive(inStream) {
inStream.on('readable', async () => { inStream.on('readable', async () => {
//console.log('inStream.readable'); //console.log('inStream.readable');
const newData = inStream.read(); const newData = inStream.read();
if (newData) { if (newData) {
this.recvBuf = Buffer.concat([this.recvBuf, newData]); this.recvBuf = Buffer.concat([this.recvBuf, newData]);
await this.#onParsePacket(); await this.onParsePacket();
} }
}); });
inStream.on('end', () => { inStream.on('end', () => {
@ -80,7 +80,7 @@ class ClientNet {
}); });
} }
async #onParsePacket() { async onParsePacket() {
let offset = 0; let offset = 0;
while (this.recvBuf.length > offset + 12) { while (this.recvBuf.length > offset + 12) {
const msgSize = this.recvBuf.readUInt16LE(offset + 0); const msgSize = this.recvBuf.readUInt16LE(offset + 0);
@ -88,7 +88,7 @@ class ClientNet {
const seqId = this.recvBuf.readUInt32LE(offset + 4); const seqId = this.recvBuf.readUInt32LE(offset + 4);
const magicCode = this.recvBuf.readUInt16LE(offset + 8); const magicCode = this.recvBuf.readUInt16LE(offset + 8);
if (this.recvBuf.length >= offset + 12 + msgSize) { if (this.recvBuf.length >= offset + 12 + msgSize) {
await this.#processMsg(msgId, await this.processMsg(msgId,
this.recvBuf.slice this.recvBuf.slice
( (
offset + 12, offset + 12,
@ -102,7 +102,7 @@ class ClientNet {
this.recvBuf = this.recvBuf.slice(offset); this.recvBuf = this.recvBuf.slice(offset);
} }
async #processMsg(msgId, buff) { async processMsg(msgId, buff) {
const handlers = this.msgHandlerMap.get(msgId); const handlers = this.msgHandlerMap.get(msgId);
if (handlers) { if (handlers) {
let msg = null; let msg = null;