This commit is contained in:
aozhiwei 2022-04-28 11:10:21 +08:00
parent 3aa216f5f2
commit 48e7b73b87
2 changed files with 53 additions and 2 deletions

View File

@ -50,6 +50,9 @@ async function start() {
await clientNet.connect();
clientNet.on('connect', () => {
console.log('onConnect');
clientNet.registerMsgHandle('SMLogin', (msg) => {
});
clientNet.sendMsg('CMLogin', {
accountId: loginData['account_id'],
sessionId: loginData['session_id'],

View File

@ -13,6 +13,8 @@ class ClientNet {
this.cmMsgId = null;
this.smMsgId = null;
this.recvBuf = Buffer.alloc(0);
this.uniqId = 1000;
this.msgHandlerMap = new Map();
}
async init() {
@ -33,6 +35,10 @@ class ClientNet {
this.on('binary', this.#onReceive.bind(this));
}
on(eventName, ...args) {
this.conn.on(eventName, ...args);
}
async #onReceive(inStream) {
inStream.on('readable', async () => {
console.log('inStream.readable');
@ -58,13 +64,55 @@ class ClientNet {
const magicCode = this.recvBuf.readUInt16LE(8);
const ext = this.recvBuf.readUInt16LE(10);
if (this.recvBuf.length >= 12 + msgSize) {
await this.#processMsg(msgId, this.recvBuf.slice(12, 12 + msgSize));
this.recvBuf = this.recvBuf.slice(12 + msgSize);
}
}
}
on(eventName, cb) {
this.conn.on(eventName, cb);
async #processMsg(msgId, buff) {
const handlers = this.msgHandlerMap.get(msgId);
if (handlers) {
let msg = null;
handlers.forEach((value, key) => {
if (!msg) {
msg = value.msgType.decode(buff);
}
console.log(msg, msg.accountInfo.userInfo.baseData.accountId);
value.cb(msg);
});
}
}
registerMsgHandle(msgName, cb) {
const msgType = this.protoPb.lookupType(msgName);
const msgId = this.smMsgId.values['_' + msgName];
if (!msgId) {
return null;
}
const handle = {
msgId: msgId,
msgName: msgName,
msgType: msgType,
cb: cb,
uniqId: ++this.uniqId}
;
if (!this.msgHandlerMap.has(msgId)) {
this.msgHandlerMap.set(msgId, new Map([
[handle.uniqId, handle]
]));
} else {
this.msgHandlerMap[msgId].set(handle.uniqId, handle);
}
return handle;
}
unRegisterMsgHandle(handle) {
if (this.msgHandlerMap.has(handle.msgId)) {
if (this.msgHandlerMap[handle.msgId].has(handle.uniqId)) {
this.msgHandlerMap[handle.msgId].delete(handle.uniqId);
}
}
}
async sendMsg(name, msg) {