This commit is contained in:
Home
2025-12-03 00:27:57 +08:00
parent 73a3d2e914
commit f250b21b38
33 changed files with 1949 additions and 473 deletions
@@ -5,20 +5,20 @@
* 协议常量类:存储协议核心配置(不可修改,确保前后端一致)
*/
export class ProtocolConst {
/** 协议版本:0~15(4位,存储在字节0低4位) */
static readonly PROTOCOL_VERSION = 0b0001;
/** 协议版本:0~15(4位,存储在字节0低4位) */
static readonly PROTOCOL_VERSION = 0b0001;
/** 头部固定长度:8字节(字节0~7,结构严格定义,不可修改) */
static readonly HEADER_SIZE = 8;
/** 头部固定长度:8字节(字节0~7,结构严格定义,不可修改) */
static readonly HEADER_SIZE = 8;
/**
* 最大包体大小:16MB(3字节长度最大支持0xFFFFFF=16777215字节≈16MB
* 4-6字节存储(24位),最大支持16MB,满足大部分场景且避免长度字段冗余
*/
static readonly MAX_BODY_SIZE = 0xFFFFFF; // 16777215字节 ≈16MB
/**
* 最大包体大小:16MB(3字节长度最大支持0xFFFFFF=16777215字节≈16MB
* 4-6字节存储(24位),最大支持16MB,满足大部分场景且避免长度字段冗余
*/
static readonly MAX_BODY_SIZE = 0xFFFFFF; // 16777215字节 ≈16MB
/** 字符串编码格式:UTF-8(统一前后端字符串编解码,避免乱码) */
static readonly STRING_ENCODING = "utf-8" as const;
/** 字符串编码格式:UTF-8(统一前后端字符串编解码,避免乱码) */
static readonly STRING_ENCODING = "utf-8" as const;
}
/**
@@ -26,11 +26,13 @@ export class ProtocolConst {
* 二进制标识,统一编码风格
*/
export enum MessageType {
PING = 0b0001, // 心跳消息(支持空包体)
AUDIO_DATA = 0b0010, // 纯音频数据
TEXT_MESSAGE = 0b0011, // 纯文本消息
CONTROL_CMD = 0b0100, // 控制指令
// 预留12种类型用于扩展(0b0100 ~ 0b1111
PING = 0b0001, // 心跳消息(支持空包体)
AUDIO_DATA = 0b0010, // 纯音频数据
TEXT_MESSAGE = 0b0011, // 纯文本消息
CONTROL_CMD = 0b0100, // 控制指令
IDENTITY = 0b0101, // 身份校验包json格式
ERROR = 0b0110 // 错误信息json格式
// 预留12种类型用于扩展(0b0100 ~ 0b1111
}
/**
@@ -38,10 +40,10 @@ export enum MessageType {
* 二进制标识,统一编码风格(1~8对应0b001~0b111
*/
export enum SerializationType {
RAW = 0b001, // 原始二进制(1
JSON = 0b010, // JSON 格式(2
STRING = 0b011, // 直接字符串(3
// 预留5种方式用于扩展(0b100 ~ 0b111
RAW = 0b001, // 原始二进制(1
JSON = 0b010, // JSON 格式(2
STRING = 0b011, // 直接字符串(3
// 预留5种方式用于扩展(0b100 ~ 0b111
}
/**
@@ -49,33 +51,33 @@ export enum SerializationType {
* 二进制标识,统一编码风格(1~8对应0b001~0b111
*/
export enum CompressionType {
NONE = 0b001, // 无压缩(1,默认值)
GZIP = 0b010, // GZIP 压缩(2
// 预留6种方式用于扩展(0b011 ~ 0b111
NONE = 0b001, // 无压缩(1,默认值)
GZIP = 0b010, // GZIP 压缩(2
// 预留6种方式用于扩展(0b011 ~ 0b111
}
/**
* 控制指令枚举(配合 MessageType.CONTROL_CMD 使用)
*/
export enum ControlCommand {
HEARTBEAT = 0b0001,
PAUSE = 0b0010,
RESUME = 0b0011,
STOP = 0b0100,
HEARTBEAT = 0b0001,
PAUSE = 0b0010,
RESUME = 0b0011,
STOP = 0b0100,
}
/**
* 解包返回结果接口
*/
export interface UnpackedResult {
msgType: MessageType;
msgTypeName: keyof typeof MessageType;
serialization: SerializationType;
serializationName: keyof typeof SerializationType;
compression: CompressionType;
compressionName: keyof typeof CompressionType;
sequence: number; // 消息顺序号(0~65535,默认0
body: Uint8Array | string | object | unknown[] | null; // PING 消息可能返回 null
msgType : MessageType;
msgTypeName : keyof typeof MessageType;
serialization : SerializationType;
serializationName : keyof typeof SerializationType;
compression : CompressionType;
compressionName : keyof typeof CompressionType;
sequence : number; // 消息顺序号(0~65535,默认0
body : Uint8Array | string | object | unknown[] | null; // PING 消息可能返回 null
}
/**
@@ -88,291 +90,276 @@ type OptionalSerialization = SerializationType | null | undefined;
* 协议编解码工具类(支持 PING 消息空包体)
*/
export class ProtocolCodec {
/**
* 打包协议包
* @param msgType 消息类型(二进制枚举,0~15)
* @param body 业务数据(PING 消息可传 null/undefined,其他类型必填)
* @param sequence 消息顺序号(0~65535,可选,默认0)
* @param serialization 序列化方式(二进制枚举,1~8,可选,自动推导)
* @param compression 压缩方式(二进制枚举,1~8,可选,默认NONE=0b001
* @returns 完整协议包
* @throws 类型错误、范围错误、包体过大等异常
*/
static pack(
msgType: MessageType,
body: PackBody = null, // 默认为 null,支持 PING 消息空包体
sequence: number = 0, // 可选参数,默认0
serialization: OptionalSerialization = null,
compression: CompressionType = CompressionType.NONE
): Uint8Array {
// 校验顺序号范围(0~65535
if (!Number.isInteger(sequence) || sequence < 0 || sequence > 0xFFFF) {
throw new RangeError(`消息顺序号必须是0~65535的整数,当前传入:${sequence}`);
}
/**
* 打包协议包
* @param msgType 消息类型(二进制枚举,0~15)
* @param body 业务数据(PING 消息可传 null/undefined,其他类型必填)
* @param sequence 消息顺序号(0~65535,可选,默认0)
* @param serialization 序列化方式(二进制枚举,1~8,可选,自动推导)
* @param compression 压缩方式(二进制枚举,1~8,可选,默认NONE=0b001
* @returns 完整协议包
* @throws 类型错误、范围错误、包体过大等异常
*/
static pack(
msgType : MessageType,
body : PackBody = null, // 默认为 null,支持 PING 消息空包体
sequence : number = 0, // 可选参数,默认0
serialization : OptionalSerialization = null,
compression : CompressionType = CompressionType.NONE
) : Uint8Array {
// 校验顺序号范围(0~65535
if (!Number.isInteger(sequence) || sequence < 0 || sequence > 0xFFFF) {
throw new RangeError(`消息顺序号必须是0~65535的整数,当前传入:${sequence}`);
}
// 特殊处理:PING 消息允许空包体,强制 RAW 序列化(空二进制)
if (msgType === MessageType.PING) {
// PING 消息忽略传入的序列化方式,强制使用 RAW(空二进制最高效)
serialization = SerializationType.RAW;
// 若传入空包体,统一处理为空 Uint8Array
body = body === null || body === undefined ? new Uint8Array(0) : body;
// PING 消息仅支持空包体或 Uint8Array(防止误传其他类型)
if (!(body instanceof Uint8Array)) {
throw new TypeError(`PING 消息仅支持空包体或 Uint8Array 类型,当前传入:${typeof body}`);
}
} else {
// 非 PING 消息:包体必填
if (body === null || body === undefined) {
throw new TypeError(`非 PING 消息(${MessageType[msgType]})包体不能为空`);
}
}
// 特殊处理:PING 消息允许空包体,强制 RAW 序列化(空二进制)
if (msgType === MessageType.PING) {
// PING 消息忽略传入的序列化方式,强制使用 RAW(空二进制最高效)
serialization = SerializationType.RAW;
// 若传入空包体,统一处理为空 Uint8Array
// body = body === null || body === undefined ? new Uint8Array(0) : body;
// PING 消息仅支持空包体或 Uint8Array(防止误传其他类型)
if (!(body instanceof Uint8Array)) {
throw new TypeError(`PING 消息仅支持空包体或 Uint8Array 类型,当前传入:${typeof body}`);
}
} else {
// 非 PING 消息:包体必填
if (body === null || body === undefined) {
throw new TypeError(`非 PING 消息(${MessageType[msgType]})包体不能为空`);
}
}
// 1. 自动推导序列化方式(非 PING 消息)
if (serialization === null || serialization === undefined && msgType !== MessageType.PING) {
if (msgType === MessageType.AUDIO_DATA) {
serialization = SerializationType.RAW;
} else if (msgType === MessageType.TEXT_MESSAGE) {
serialization = SerializationType.STRING;
} else if (msgType === MessageType.CONTROL_CMD) {
serialization = SerializationType.JSON;
} else {
throw new Error(`不支持的消息类型:${MessageType[msgType]}(值:${msgType}`);
}
}
// 1. 自动推导序列化方式(非 PING 消息)
if (serialization === null || serialization === undefined && msgType !== MessageType.PING) {
if (msgType === MessageType.AUDIO_DATA) {
serialization = SerializationType.RAW;
} else if (msgType === MessageType.TEXT_MESSAGE) {
serialization = SerializationType.STRING;
} else if (msgType === MessageType.CONTROL_CMD) {
serialization = SerializationType.JSON;
} else if (msgType === MessageType.IDENTITY) {
serialization = SerializationType.JSON;
} else if (msgType === MessageType.ERROR) {
serialization = SerializationType.JSON;
} else {
throw new Error(`不支持的消息类型:${MessageType[msgType]}(值:${msgType}`);
}
}
// 2. 校验枚举值范围(3位存储,1~8即0b001~0b111
if (serialization < 0b001 || serialization > 0b111) {
throw new RangeError(`序列化方式必须在1~8(0b001~0b111)范围内,当前传入:${serialization}0b${serialization.toString(2).padStart(3, '0')}`);
}
if (compression < 0b001 || compression > 0b111) {
throw new RangeError(`压缩方式必须在1~8(0b001~0b111)范围内,当前传入:${compression}0b${compression.toString(2).padStart(3, '0')}`);
}
// 2. 校验枚举值范围(3位存储,1~8即0b001~0b111
if (serialization < 0b001 || serialization > 0b111) {
throw new RangeError(`序列化方式必须在1~8(0b001~0b111)范围内,当前传入:${serialization}0b${serialization.toString(2).padStart(3, '0')}`);
}
if (compression < 0b001 || compression > 0b111) {
throw new RangeError(`压缩方式必须在1~8(0b001~0b111)范围内,当前传入:${compression}0b${compression.toString(2).padStart(3, '0')}`);
}
// 3. 序列化包体
let serializedBody: Uint8Array;
const textEncoder = new TextEncoder();
// 3. 序列化包体
let serializedBody : Uint8Array;
const textEncoder = new TextEncoder();
switch (serialization) {
case SerializationType.RAW:
// RAW 序列化:支持 Uint8ArrayPING 消息可能是空 Uint8Array
if (!(body instanceof Uint8Array)) {
throw new TypeError(`RAW 序列化要求 body 必须是 Uint8Array 类型,当前传入:${typeof body}`);
}
serializedBody = body;
break;
switch (serialization) {
case SerializationType.RAW:
// RAW 序列化:支持 Uint8ArrayPING 消息可能是空 Uint8Array
// if (!(body instanceof Uint8Array)) {
// throw new TypeError(`RAW 序列化要求 body 必须是 Uint8Array 类型,当前传入:${typeof body}`);
// }
serializedBody = body instanceof Uint8Array ? body : new Uint8Array(body as ArrayBuffer);
break;
case SerializationType.STRING:
// STRING 序列化:必须传入字符串(非 PING 消息已校验非空)
if (typeof body !== "string") {
throw new TypeError(`STRING 序列化要求 body 必须是 string 类型,当前传入:${typeof body}`);
}
serializedBody = textEncoder.encode(body);
break;
case SerializationType.STRING:
// STRING 序列化:必须传入字符串(非 PING 消息已校验非空)
serializedBody = textEncoder.encode(body as string);
break;
case SerializationType.JSON:
// JSON 序列化:支持字符串、对象、数组(非 PING 消息已校验非空)
if (typeof body === "string") {
serializedBody = textEncoder.encode(body);
} else if (typeof body === "object" && body !== null) {
const jsonStr = JSON.stringify(body);
serializedBody = textEncoder.encode(jsonStr);
} else {
throw new TypeError(`JSON 序列化要求 body 必须是 string/object/array 类型,当前传入:${typeof body}`);
}
break;
case SerializationType.JSON:
// 断言:body 是 string 或 object
if (typeof body === 'string') {
serializedBody = textEncoder.encode(body);
} else {
serializedBody = textEncoder.encode(JSON.stringify(body));
}
break;
default:
throw new Error(`不支持的序列化方式:${SerializationType[serialization]}(值:${serialization}0b${serialization.toString(2).padStart(3, '0')}`);
}
default:
throw new Error(`不支持的序列化方式:${SerializationType[serialization]}(值:${serialization}0b${serialization.toString(2).padStart(3, '0')}`);
}
// 4. 压缩包体
let compressedBody: Uint8Array;
if (compression === CompressionType.NONE) {
compressedBody = serializedBody;
} else if (compression === CompressionType.GZIP) {
// 若需启用GZIP,取消注释下方代码(需导入pako)
// try {
// compressedBody = pako.gzip(serializedBody);
// } catch (e) {
// throw new Error(`GZIP 压缩失败:${(e as Error).message}`);
// }
throw new Error("GZIP 压缩暂未启用,请导入pako库并取消对应代码注释");
} else {
throw new Error(`不支持的压缩方式:${CompressionType[compression]}(值:${compression}0b${compression.toString(2).padStart(3, '0')}`);
}
// 4. 压缩:暂不支持,直接赋值
const compressedBody = serializedBody;
// 5. 校验包体大小(24位长度最大支持0xFFFFFF=16777215字节)
const bodyLen = compressedBody.length;
if (bodyLen > ProtocolConst.MAX_BODY_SIZE) {
throw new Error(
`包体过大(${bodyLen}字节),最大支持${ProtocolConst.MAX_BODY_SIZE}字节(≈16MB`
);
}
// 5. 校验包体大小(24位长度最大支持0xFFFFFF=16777215字节)
const bodyLen = compressedBody.length;
if (bodyLen > ProtocolConst.MAX_BODY_SIZE) {
throw new Error(
`包体过大(${bodyLen}字节),最大支持${ProtocolConst.MAX_BODY_SIZE}字节(≈16MB`
);
}
// 6. 构造头部(8字节,按最新结构)
const header = new Uint8Array(ProtocolConst.HEADER_SIZE);
// 6. 构造头部(8字节,按最新结构)
const header = new Uint8Array(ProtocolConst.HEADER_SIZE);
// 字节0:消息类型(高4位) + 协议版本(低4位)
header[0] = ((msgType & 0x0F) << 4) | (ProtocolConst.PROTOCOL_VERSION & 0x0F);
// 字节0:消息类型(高4位) + 协议版本(低4位)
header[0] = ((msgType & 0x0F) << 4) | (ProtocolConst.PROTOCOL_VERSION & 0x0F);
// 字节1:序列化方式(高3位) + 压缩方式(中3位) + 保留位(低2位,填0)
header[1] = ((serialization & 0x07) << 5) | ((compression & 0x07) << 2) | 0x00;
// 字节1:序列化方式(高3位) + 压缩方式(中3位) + 保留位(低2位,填0)
header[1] = ((serialization & 0x07) << 5) | ((compression & 0x07) << 2) | 0x00;
// 字节2~3:消息顺序号(16位大端序,0~65535)
header[2] = (sequence >> 8) & 0xFF; // 顺序号高8位
header[3] = sequence & 0xFF; // 顺序号低8位
// 字节2~3:消息顺序号(16位大端序,0~65535)
header[2] = (sequence >> 8) & 0xFF; // 顺序号高8位
header[3] = sequence & 0xFF; // 顺序号低8位
// 字节4~6:消息体长度(24位大端序,0~0xFFFFFF
header[4] = (bodyLen >> 16) & 0xFF; // 长度高8位
header[5] = (bodyLen >> 8) & 0xFF; // 长度中8位
header[6] = bodyLen & 0xFF; // 长度低8位
// 字节4~6:消息体长度(24位大端序,0~0xFFFFFF
header[4] = (bodyLen >> 16) & 0xFF; // 长度高8位
header[5] = (bodyLen >> 8) & 0xFF; // 长度中8位
header[6] = bodyLen & 0xFF; // 长度低8位
// 字节7:保留位(固定填0x00)
header[7] = 0x00;
// 字节7:保留位(固定填0x00)
header[7] = 0x00;
// 7. 拼接头部和包体
const totalLen = ProtocolConst.HEADER_SIZE + bodyLen;
const packet = new Uint8Array(totalLen);
packet.set(header, 0);
packet.set(compressedBody, ProtocolConst.HEADER_SIZE);
// 7. 拼接头部和包体
const totalLen = ProtocolConst.HEADER_SIZE + bodyLen;
const packet = new Uint8Array(totalLen);
packet.set(header, 0);
packet.set(compressedBody, ProtocolConst.HEADER_SIZE);
return packet;
}
return packet;
}
/**
* 解包协议包
* @param packet 完整协议包
* @returns 结构化解包结果(含顺序号)
* @throws 各种解析异常
*/
static unpack(packet: Uint8Array | ArrayBuffer): UnpackedResult {
const uint8Packet = packet instanceof ArrayBuffer
? new Uint8Array(packet)
: packet;
/**
* 解包协议包
* @param packet 完整协议包
* @returns 结构化解包结果(含顺序号)
* @throws 各种解析异常
*/
static unpack(packet : Uint8Array | ArrayBuffer) : UnpackedResult {
const uint8Packet = packet instanceof ArrayBuffer
? new Uint8Array(packet)
: packet;
// 1. 校验包长度(至少8字节头部)
if (uint8Packet.length < ProtocolConst.HEADER_SIZE) {
throw new Error(
`包长度过短(${uint8Packet.length}字节),至少需要${ProtocolConst.HEADER_SIZE}字节头部`
);
}
// 1. 校验包长度(至少8字节头部)
if (uint8Packet.length < ProtocolConst.HEADER_SIZE) {
throw new Error(
`包长度过短(${uint8Packet.length}字节),至少需要${ProtocolConst.HEADER_SIZE}字节头部`
);
}
// 2. 拆分头部和包体
const header = uint8Packet.subarray(0, ProtocolConst.HEADER_SIZE);
const bodyBuffer = uint8Packet.subarray(ProtocolConst.HEADER_SIZE);
// 2. 拆分头部和包体
const header = uint8Packet.subarray(0, ProtocolConst.HEADER_SIZE);
const bodyBuffer = uint8Packet.subarray(ProtocolConst.HEADER_SIZE);
// 3. 解析头部字段
// 字节0:消息类型(高4位) + 协议版本(低4位)
const byte0 = header[0];
const msgType = (byte0 >> 4) & 0x0F; // 消息类型(0~15
const version = byte0 & 0x0F; // 协议版本(0~15
// 3. 解析头部字段
// 字节0:消息类型(高4位) + 协议版本(低4位)
const byte0 = header[0];
const msgType = (byte0 >> 4) & 0x0F; // 消息类型(0~15
const version = byte0 & 0x0F; // 协议版本(0~15
// 校验消息类型
if (!Object.values(MessageType).includes(msgType as MessageType)) {
throw new Error(`非法消息类型:${msgType}0b${msgType.toString(2).padStart(4, '0')}`);
}
// 校验消息类型
if (!Object.values(MessageType).includes(msgType as MessageType)) {
throw new Error(`非法消息类型:${msgType}0b${msgType.toString(2).padStart(4, '0')}`);
}
// 校验版本
if (version !== ProtocolConst.PROTOCOL_VERSION) {
throw new Error(
`协议版本不匹配:收到v${version}0b${version.toString(2).padStart(4, '0')}),当前支持v${ProtocolConst.PROTOCOL_VERSION}0b${ProtocolConst.PROTOCOL_VERSION.toString(2).padStart(4, '0')}`
);
}
// 校验版本
if (version !== ProtocolConst.PROTOCOL_VERSION) {
throw new Error(
`协议版本不匹配:收到v${version}0b${version.toString(2).padStart(4, '0')}),当前支持v${ProtocolConst.PROTOCOL_VERSION}0b${ProtocolConst.PROTOCOL_VERSION.toString(2).padStart(4, '0')}`
);
}
// 字节1:序列化方式(高3位) + 压缩方式(中3位) + 保留位(低2位)
const byte1 = header[1];
const serialization = (byte1 >> 5) & 0x07; // 高3位(1~8
const compression = (byte1 >> 2) & 0x07; // 中3位(1~8
// 保留位:(byte1 & 0x03),暂不处理
// 字节1:序列化方式(高3位) + 压缩方式(中3位) + 保留位(低2位)
const byte1 = header[1];
const serialization = (byte1 >> 5) & 0x07; // 高3位(1~8
const compression = (byte1 >> 2) & 0x07; // 中3位(1~8
// 保留位:(byte1 & 0x03),暂不处理
// 校验序列化方式
if (!Object.values(SerializationType).includes(serialization as SerializationType)) {
throw new Error(`非法序列化方式:${serialization}0b${serialization.toString(2).padStart(3, '0')}`);
}
// 校验序列化方式
if (!Object.values(SerializationType).includes(serialization as SerializationType)) {
throw new Error(`非法序列化方式:${serialization}0b${serialization.toString(2).padStart(3, '0')}`);
}
// 校验压缩方式
if (!Object.values(CompressionType).includes(compression as CompressionType)) {
throw new Error(`非法压缩方式:${compression}0b${compression.toString(2).padStart(3, '0')}`);
}
// 校验压缩方式
if (!Object.values(CompressionType).includes(compression as CompressionType)) {
throw new Error(`非法压缩方式:${compression}0b${compression.toString(2).padStart(3, '0')}`);
}
// 字节2~3:消息顺序号(16位大端序)
const sequence = (header[2] << 8) | header[3]; // 0~65535
// 字节2~3:消息顺序号(16位大端序)
const sequence = (header[2] << 8) | header[3]; // 0~65535
// 字节4~6:消息体长度(24位大端序),字节7:保留位(忽略)
const bodyLen = (header[4] << 16) | (header[5] << 8) | header[6];
// 字节4~6:消息体长度(24位大端序),字节7:保留位(忽略)
const bodyLen = (header[4] << 16) | (header[5] << 8) | header[6];
// 校验包体长度(空包体时 bodyBuffer.length 应为0
if (bodyBuffer.length !== bodyLen) {
throw new Error(
`包体长度不匹配:头部声明${bodyLen}字节,实际接收${bodyBuffer.length}字节`
);
}
// 校验包体长度(空包体时 bodyBuffer.length 应为0
if (bodyBuffer.length !== bodyLen) {
throw new Error(
`包体长度不匹配:头部声明${bodyLen}字节,实际接收${bodyBuffer.length}字节`
);
}
// 4. 解压包体
let decompressedBody: Uint8Array;
if (compression === CompressionType.NONE) {
decompressedBody = bodyBuffer;
} else if (compression === CompressionType.GZIP) {
// 若需启用GZIP,取消注释下方代码
// try {
// decompressedBody = pako.ungzip(bodyBuffer);
// } catch (e) {
// throw new Error(`GZIP 解压失败:${(e as Error).message}`);
// }
throw new Error("GZIP 解压暂未启用,请导入pako库并取消对应代码注释");
} else {
throw new Error(`不支持的压缩方式:${CompressionType[compression]}(值:${compression}0b${compression.toString(2).padStart(3, '0')}`);
}
// 4. 解压包体
let decompressedBody : Uint8Array;
if (compression === CompressionType.NONE) {
decompressedBody = bodyBuffer;
} else if (compression === CompressionType.GZIP) {
// 若需启用GZIP,取消注释下方代码
// try {
// decompressedBody = pako.ungzip(bodyBuffer);
// } catch (e) {
// throw new Error(`GZIP 解压失败:${(e as Error).message}`);
// }
throw new Error("GZIP 解压暂未启用,请导入pako库并取消对应代码注释");
} else {
throw new Error(`不支持的压缩方式:${CompressionType[compression]}(值:${compression}0b${compression.toString(2).padStart(3, '0')}`);
}
// 5. 反序列化包体(PING 消息空包体返回 null)
let body: UnpackedResult["body"];
const textDecoder = new TextDecoder();
// 5. 反序列化包体(PING 消息空包体返回 null)
let body : UnpackedResult["body"];
const textDecoder = new TextDecoder();
// 特殊处理:空包体(PING 消息常见)返回 null
if (decompressedBody.length === 0) {
body = null;
} else {
switch (serialization) {
case SerializationType.RAW:
body = decompressedBody;
break;
// 特殊处理:空包体(PING 消息常见)返回 null
if (decompressedBody.length === 0) {
body = null;
} else {
switch (serialization) {
case SerializationType.RAW:
body = decompressedBody;
break;
case SerializationType.STRING:
try {
body = textDecoder.decode(decompressedBody);
} catch (e) {
throw new Error(`STRING 反序列化失败:UTF-8 解码错误`);
}
break;
case SerializationType.STRING:
try {
body = textDecoder.decode(decompressedBody);
} catch (e) {
throw new Error(`STRING 反序列化失败:UTF-8 解码错误`);
}
break;
case SerializationType.JSON:
try {
const jsonStr = textDecoder.decode(decompressedBody);
body = JSON.parse(jsonStr);
} catch (e) {
if (e instanceof SyntaxError) {
throw new Error(`JSON 反序列化失败:格式错误(${(e as Error).message}`);
} else {
throw new Error(`JSON 反序列化失败:${(e as Error).message}`);
}
}
break;
case SerializationType.JSON:
try {
const jsonStr = textDecoder.decode(decompressedBody);
body = JSON.parse(jsonStr);
} catch (e) {
if (e instanceof SyntaxError) {
throw new Error(`JSON 反序列化失败:格式错误(${(e as Error).message}`);
} else {
throw new Error(`JSON 反序列化失败:${(e as Error).message}`);
}
}
break;
default:
throw new Error(`不支持的序列化方式:${SerializationType[serialization]}(值:${serialization}0b${serialization.toString(2).padStart(3, '0')}`);
}
}
default:
throw new Error(`不支持的序列化方式:${SerializationType[serialization]}(值:${serialization}0b${serialization.toString(2).padStart(3, '0')}`);
}
}
// 6. 返回解包结果
return {
msgType: msgType as MessageType,
msgTypeName: MessageType[msgType] as keyof typeof MessageType,
serialization: serialization as SerializationType,
serializationName: SerializationType[serialization] as keyof typeof SerializationType,
compression: compression as CompressionType,
compressionName: CompressionType[compression] as keyof typeof CompressionType,
sequence: sequence,
body: body,
};
}
// 6. 返回解包结果
return {
msgType: msgType as MessageType,
msgTypeName: MessageType[msgType] as keyof typeof MessageType,
serialization: serialization as SerializationType,
serializationName: SerializationType[serialization] as keyof typeof SerializationType,
compression: compression as CompressionType,
compressionName: CompressionType[compression] as keyof typeof CompressionType,
sequence: sequence,
body: body,
};
}
}
@@ -0,0 +1,104 @@
<template>
<view class="container">
<button @click="onStartRecord" :disabled="isRecording">开始录音</button>
<button @click="onStopRecord" :disabled="!isRecording">停止录音</button>
<view class="tip">{{ status }}</view>
<view class="tip">当前分贝{{ currentDecibels }}</view>
<yao-RecordFrame
ref="recordFrame"
@onFrameRecorded="frameRecorded"
@currentDecibels="onCurrentDecibels"
@onStop="stopIt"
></yao-RecordFrame>
<sdx-StreamPlayer ref="aaa">xx</sdx-StreamPlayer>
<button @click="callPhone">接通电话</button>
</view>
</template>
<script setup>
import { onMounted, onUnmounted } from 'vue';
import {
ProtocolCodec,
MessageType,
SerializationType,
CompressionType,
ControlCommand,
ProtocolConst
} from './ProtocolCodec';
import { ref } from 'vue';
import useWebSocket from './useWebSocket';
const { state, connect, disconnect, sendBinary } = useWebSocket(
'ws://127.0.0.1:8000/ws/audio',
{
// 身份校验信息(从登录态获取)
identity: {
user_id: '1001',
token: 'your_auth_token',
name: '测试用户'
},
reconnectDelay: 5000,
// 🔴 1. 消息回调:接收服务端所有消息(含身份响应、错误、自定义消息)
onMessage: ({ msgType, data, rawData }) => {
console.log('收到服务端消息', { msgType, data });
},
// 🔴 2. 身份校验成功回调:仅在身份校验通过后触发
onAuthSuccess: (context) => {
console.log('身份校验成功!上下文信息:', context);
},
// 🔴 3. 连接关闭回调:连接关闭时触发(含主动关闭、异常关闭)
onClose: (closeInfo) => {
console.log('连接关闭', closeInfo);
}
}
);
// 2. 示例:发送音频帧
const sendAudioFrame = (frameBuffer) => {
// if (!state.isConnected) {
// console.warn('未连接,无法发送音频帧');
// return;
// }
};
const callPhone = () => {
connect()
}
const frameRecorded =() =>{}
// 组件挂载时初始化连接
onMounted(() => {
});
// 组件卸载时关闭连接(可选)
onUnmounted(() => {
});
</script>
<style scoped>
.container {
padding: 20rpx;
}
button {
margin: 10rpx 0;
padding: 15rpx 30rpx;
background: #007aff;
color: white;
border: none;
border-radius: 8rpx;
}
button:disabled {
background: #ccc;
}
.tip {
margin: 15rpx 0;
font-size: 28rpx;
color: #333;
}
</style>
+211 -22
View File
@@ -4,40 +4,229 @@
<button @click="onStopRecord" :disabled="!isRecording">停止录音</button>
<view class="tip">{{ status }}</view>
<view class="tip">当前分贝{{ currentDecibels }}</view>
<yao-RecordFrame
ref="recordFrame"
@onFrameRecorded="frameRecorded"
@currentDecibels="onCurrentDecibels"
@onStop="stopIt"
></yao-RecordFrame>
<yao-RecordFrame ref="recordFrame" @onFrameRecorded="frameRecorded" @currentDecibels="onCurrentDecibels"
@onStop="stopIt">
</yao-RecordFrame>
<sdx-StreamPlayer ref="aaa">xx</sdx-StreamPlayer>
<button @click="callPhone">接通电话</button>
<button @click="test">接通电话</button>
</view>
</template>
<script setup>
import { onMounted, onUnmounted } from 'vue';
<script>
import {
ProtocolCodec,
MessageType,
SerializationType,
CompressionType,
ControlCommand,
ProtocolConst
ProtocolConst,
} from './ProtocolCodec'; // 确保协议文件也是 ESModule 格式(export 导出)
import { ref } from 'vue';
import useWebSocket from './useWebSocket';
const { initWebSocket, closeWebSocket } = useWebSocket();
export default {
data() {
return {
status: "未录音",
currentDecibels: 0,
isRecording: false,
ws: null, // WebSocket 实例
audioContext: null, // 音频上下文
scriptProcessor: null, // 音频处理节点
audioBufferSource: null, // 音频源节点
frameBufferList: [], // 缓存音频帧
wsUrl: "ws://127.0.0.1:8000/ws/audio", // 替换为实际后端地址
};
},
onUnload() {
// 页面卸载时清理资源
this.stopRecordAndClean();
},
methods: {
// 组件挂载时初始化连接
onMounted(() => {
initWebSocket();
});
test() {
this.ws = uni.connectSocket({
url: this.wsUrl,
fail: () => {
console.log('fail');
},
success: () => {
console.log('web');
// 组件卸载时关闭连接(可选)
onUnmounted(() => {
closeWebSocket();
});
},
fail: () => {
console.log('fail');
},
});
this.ws.onOpen((res) => {
console.log('WebSocket连接已打开', res);
this.ws.send({
data: ProtocolCodec.pack(MessageType.IDENTITY, {
user_id: '1001',
token: 'your_auth_token',
name: '测试用户'
})
});
});
this.ws.onMessage((res) => {
const {
msgType,
body
} = ProtocolCodec.unpack(res.data)
if (msgType === MessageType.IDENTITY) {
if (body?.code === 200) {
console.log('身份校验成功');
}
this.onStartRecord()
}
// 处理不同类型的数据
// if (typeof messageData === 'string') {
// // 文本数据
// try {
// const parsedData = JSON.parse(messageData);
// this.handleMessage(parsedData);
// } catch (e) {
// this.handleMessage(messageData);
// }
// } else if (messageData instanceof ArrayBuffer) {
// // 二进制数据
// try {
// this.$refs.aaa.appendBuffer(messageData)
// // const str = this.arrayBufferToStringCompat(messageData);
// // console.log('转换后的字符串:', str);
// } catch (e) {
// console.log('二进制数据解析失败:', e);
// }
// }
})
},
// 申请录音权限
async applyRecordPermission() {
try {
const res = await uni.requestPermissions({
scope: "scope.record"
});
const isGranted = res[0].grantStatus === 1;
if (!isGranted) {
uni.showToast({
title: "请授予录音权限",
icon: "none"
});
}
return isGranted;
} catch (e) {
console.error("申请权限失败:", e);
return false;
}
},
// ArrayBuffer 转字符串
// 兼容的 ArrayBuffer 转字符串方法
arrayBufferToStringCompat(buffer) {
// 方法1: 使用 String.fromCharCode 和 Uint8Array
const uint8Array = new Uint8Array(buffer);
let str = '';
for (let i = 0; i < uint8Array.length; i++) {
str += String.fromCharCode(uint8Array[i]);
}
return str;
// 方法2: 或者使用更简洁的方式
// return String.fromCharCode.apply(null, new Uint8Array(buffer));
},
// 开始录音
onStartRecord() {
try {
this.$refs.recordFrame.start({
sampleRate: 16000,
frameSize: 1024,
gain: 1.0,
onFrameRecorded: ({
isLastFrame,
frameBuffer
}) => {
this.ws.send({
data: ProtocolCodec.pack(MessageType.AUDIO_DATA, frameBuffer)
});
},
onDecibels: (decibels) => {
this.currentDecibels = decibels;
}
});
this.isRecording = true;
this.status = "录音中...";
} catch (e) {
console.error("启动录音失败:", e);
this.status = "启动录音失败";
this.isRecording = false;
}
},
// 停止录音
onStopRecord() {
this.stopRecordAndClean();
},
// 停止录音并清理资源
stopRecordAndClean() {
if (this.isRecording) {
// 停止录音组件
this.$refs.recordFrame.stop();
this.isRecording = false;
this.status = "已停止录音";
}
// 关闭 WebSocket
if (this.ws) {
this.ws.close();
this.ws = null;
}
// 清理音频上下文
if (this.audioContext) {
this.audioContext.close();
this.audioContext = null;
this.scriptProcessor = null;
this.frameBufferList = [];
}
// 重置状态
this.currentDecibels = 0;
},
// 接收音频帧并处理
frameRecorded({
isLastFrame,
frameBuffer
}) {
// console.log("收到音频帧:", isLastFrame, frameBuffer.length);
// 2. 通过 WebSocket 发送给后端
if (this.ws) {
try {
this.ws.send({
data: frameBuffer
});
} catch (e) {
console.error("发送音频帧失败:", e);
}
}
},
// 监听分贝值
onCurrentDecibels(decibels) {
// this.currentDecibels = decibels.toFixed(2);
// console.log("当前分贝:", this.currentDecibels);
},
// 录音停止回调
stopIt(base64) {
this.stopRecordAndClean();
console.log("录音停止,最终音频Base64", base64?.substring(0, 50) + "...");
},
},
};
</script>
<style scoped>
@@ -63,4 +252,4 @@
font-size: 28rpx;
color: #333;
}
</style>
</style>
@@ -1,77 +1,271 @@
import { ref } from 'vue';
// src/hooks/useWebSocket.js
import { ref, onUnmounted, computed } from 'vue';
import { ProtocolCodec, MessageType } from './ProtocolCodec';
// 在组件 setup 函数中使用
export default function useWebSocket() {
// 存储 WebSocket 实例
const ws = ref(null);
const wsUrl = 'ws://127.0.0.1:8000/ws/audio';
// 初始化 WebSocket 连接
const initWebSocket = () => {
ws.value = uni.connectSocket({
url: wsUrl,
success: () => {
console.log('web');
// 监听连接打开
ws.value.onOpen((res) => {
console.log('WebSocket连接已打开', res);
// 监听消息接收
ws.value.onMessage((res) => {
let messageData = res.data;
// 处理不同类型的数据
if (typeof messageData === 'string') {
// 文本数据
try {
const parsedData = JSON.parse(messageData);
handleMessage(parsedData);
} catch (e) {
handleMessage(messageData);
}
} else if (messageData instanceof ArrayBuffer) {
// 二进制数据
try {
// 注意:组合式 API 中需通过 ref 获取子组件实例
const aaaRef = ref(null); // 需在组件中声明 <component ref="aaaRef" />
aaaRef.value?.appendBuffer(messageData);
} catch (e) {
console.log('二进制数据解析失败:', e);
}
}
});
});
},
fail: () => {
console.log('fail');
},
});
export default function useWebSocket(url, options = {}) {
// 使用模块级变量存储 SocketTask
let socketTask = null;
let reconnectTimer = null;
// 配置合并
const _defaultOptions = {
identity: {},
protocols: ['binary'],
reconnectDelay: 3000,
onMessage: () => {},
onAuthSuccess: () => {},
onClose: () => {},
...options
};
// 消息处理函数(根据实际业务逻辑修改)
const handleMessage = (data) => {
// 原组件中的 handleMessage 逻辑迁移到这里
console.log('收到消息:', data);
};
// 响应式状态
const state = ref({
isConnected: false,
isConnecting: false,
error: null,
clientId: '',
context: null
});
// 辅助函数:ArrayBuffer 转字符串(如果后续需要使用)
const arrayBufferToStringCompat = (buffer) => {
const decoder = new TextDecoder('utf-8');
return decoder.decode(buffer);
};
// 关闭连接函数(可选,按需暴露)
const closeWebSocket = () => {
if (ws.value) {
ws.value.close();
console.log('WebSocket连接已关闭');
// 清理连接
const cleanupSocket = () => {
if (socketTask) {
try {
socketTask.close({ code: 1008, reason: '主动关闭' });
} catch (e) {
console.warn('关闭连接时出错:', e);
}
socketTask = null;
}
state.value = {
isConnected: false,
isConnecting: false,
error: null,
clientId: '',
context: null
};
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
};
return {
ws,
initWebSocket,
closeWebSocket,
handleMessage
// 发送消息
const sendMessage = (data, isBinary = true) => {
return new Promise((resolve, reject) => {
if (!socketTask || !state.value.isConnected) {
const err = new Error('WebSocket 未连接');
state.value.error = err;
return reject(err);
}
const sendData = isBinary ? data : JSON.stringify(data);
socketTask.send({
data: sendData,
success: () => resolve(),
fail: (err) => {
console.error('消息发送失败:', err);
reject(new Error(`发送失败: ${err.errMsg || err.message}`));
}
});
});
};
};
// 发送身份校验包
const sendIdentityPacket = async () => {
const { user_id, token, name } = _defaultOptions.identity;
if (!user_id || !token) {
state.value.error = new Error('身份校验信息缺失(user_id/token');
cleanupSocket();
return;
}
const identityPacket = ProtocolCodec.pack(MessageType.IDENTITY, {
user_id,
token,
name: name || `用户${user_id}`
});
try {
await sendMessage(identityPacket);
} catch (err) {
console.error('身份校验包发送失败', err);
cleanupSocket();
reconnectSocket();
}
};
// 处理服务端消息
const handleServerMessage = (res) => {
try {
const { data } = res;
let msgType, bodyData;
// 兼容不同数据格式
if (data instanceof ArrayBuffer) {
const uint8Array = new Uint8Array(data);
[msgType, _, bodyData] = ProtocolCodec.unpack(uint8Array);
} else if (typeof data === 'string') {
// 如果是字符串,可能是文本消息
console.warn('收到非二进制消息:', data);
return;
} else {
console.warn('未知的消息数据类型:', typeof data, data);
return;
}
const bodyStr = bodyData.toString('utf-8');
const parsedBody = bodyStr ? JSON.parse(bodyStr) : {};
if (msgType === MessageType.IDENTITY_RESP) {
state.value.context = parsedBody.data;
state.value.clientId = parsedBody.data?.client_id || '';
_defaultOptions.onAuthSuccess(parsedBody.data);
}
_defaultOptions.onMessage({
msgType,
data: parsedBody,
rawData: data
});
} catch (err) {
console.error('消息处理错误:', err);
state.value.error = new Error(`消息解析失败:${err.message}`);
_defaultOptions.onMessage({
msgType: 'ERROR',
data: { message: err.message },
rawData: res.data
});
}
};
// 初始化连接
const initSocket = () => {
if (state.value.isConnecting || state.value.isConnected) {
console.log('连接已存在或正在连接中,跳过重复连接');
return;
}
state.value.isConnecting = true;
state.value.error = null;
console.log('发起 WebSocket 连接:', url);
// 创建连接
socketTask = uni.connectSocket({
url,
protocols: _defaultOptions.protocols,
success: () => {
console.log('connectSocket API 调用成功');
},
fail: (err) => {
console.error('connectSocket API 调用失败:', err);
state.value.error = new Error(`连接创建失败:${err.errMsg || err.message}`);
state.value.isConnecting = false;
reconnectSocket();
}
});
socketTask.onOpen(() => {
console.log('xxxxxxxx');
})
// 检查实例是否有效
if (!socketTask) {
console.error('SocketTask 实例创建失败');
state.value.error = new Error('SocketTask 实例为空');
state.value.isConnecting = false;
reconnectSocket();
return;
}
// 绑定事件处理器
const openHandler = () => {
console.log('=== WebSocket 连接成功 ===');
state.value.isConnecting = false;
state.value.isConnected = true;
clearTimeout(reconnectTimer);
sendIdentityPacket();
};
const messageHandler = handleServerMessage;
const closeHandler = (res) => {
console.log('=== WebSocket 连接关闭 ===', res);
const closeInfo = {
code: res.code,
reason: res.reason,
isManual: res.code === 1008
};
_defaultOptions.onClose(closeInfo);
state.value.isConnected = false;
state.value.isConnecting = false;
if (!closeInfo.isManual && res.code !== 1000) {
reconnectSocket();
}
};
const errorHandler = (err) => {
console.log('=== WebSocket 连接错误 ===', err);
state.value.error = new Error(`连接错误:${err.errMsg || err.message}`);
state.value.isConnecting = false;
state.value.isConnected = false;
reconnectSocket();
};
// 绑定事件
socketTask.onOpen(openHandler);
socketTask.onMessage(messageHandler);
socketTask.onClose(closeHandler);
socketTask.onError(errorHandler);
// 存储事件处理器以便清理
socketTask._handlers = {
open: openHandler,
message: messageHandler,
close: closeHandler,
error: errorHandler
};
};
// 重连逻辑
const reconnectSocket = () => {
if (reconnectTimer) clearTimeout(reconnectTimer);
reconnectTimer = setTimeout(() => {
console.log(`尝试重连(延迟${_defaultOptions.reconnectDelay}ms`);
initSocket();
}, _defaultOptions.reconnectDelay);
};
// 断开连接并停止重连
const disconnect = () => {
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
cleanupSocket();
};
// 对外暴露的方法
const actions = {
connect: initSocket,
disconnect,
sendBinary: (data) => sendMessage(data, true),
sendJson: (data) => sendMessage(data, false),
reconnect: reconnectSocket
};
// 组件卸载清理
onUnmounted(() => {
disconnect();
});
return {
state: computed(() => ({ ...state.value })),
...actions
};
}
@@ -1,8 +1,8 @@
{
"hash": "56a2a6b1",
"configHash": "0d2436b6",
"lockfileHash": "1c743963",
"browserHash": "42eed156",
"hash": "030e727a",
"configHash": "c22f3258",
"lockfileHash": "c10b225f",
"browserHash": "77dd6173",
"optimized": {},
"chunks": {}
}