gameClient/assets/scripts/network/messageDecoder.ts

51 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// MessageDecoder.ts
import * as pb from './pbExport'
export class MessageDecoder {
// 消息ID与消息类的映射表
private static _messageClasses: Map<number, (buffer: Uint8Array) => any> = new Map()
/**
* 注册消息类(启动时调用)
* @param msgId 消息ID
* @param decoder 解码函数(如 pb.ReqUserLogin.decode
*/
public static Register<T>(msgId: number, decoder: (buffer: Uint8Array) => T): void {
this._messageClasses.set(msgId, decoder)
}
/**
* 解码消息根据ID动态实例化对应消息类
* @param msgId 消息ID
* @param buffer 原始消息Uint8Array
* @returns 解码后的消息对象
*/
public static Decode(msgId: number, buffer: Uint8Array): [any, Error] {
try {
const decoder = this._messageClasses.get(msgId)
if (!decoder) {
return [null, new Error(`未注册的消息ID: ${msgId}`)]
}
// 实例化消息类并解码数据
const instance = decoder(buffer)
return [instance, null]
} catch (err) {
return [null, new Error(`解消息: ${msgId} 失败。err:${err}`)]
}
}
/**
* 字节流转换成Hex码
* @param buffer 原始消息Uint8Array
* @returns 字节流转换成Hex码
*/
public static Uint8ToHex(buffer: Uint8Array): string {
return Array.from(buffer)
.map((byte) => byte.toString(16).padStart(2, '0'))
.join(' ')
}
}
MessageDecoder.Register(pb.MsgId.ReqUserLoginId, pb.ReqUserLogin.decode)
MessageDecoder.Register(pb.MsgId.RspUserLoginId, pb.RspUserLogin.decode)