规则:消息体长度+消息体(消息体长度4个字节)
/**
- 字节流工具类
*/
export default class ByteArray {
/**
* 组包
* 1.uint8Array-原数组
* 2.megType-消息类型
* 最后写入长度返回
*/
EncodePack(uint8Array: Uint8Array, megType: number): Uint8Array {
let newUint8Array: Uint8Array = new Uint8Array(uint8Array.length + 2);
let arrayBuffer = new ArrayBuffer(2);
var dv = new DataView(arrayBuffer);
dv.setUint16(0, megType, true);
let uint8Array0 = new Uint8Array(arrayBuffer);
newUint8Array.set(uint8Array0);
newUint8Array.set(uint8Array, uint8Array0.length);
console.log("写类型newUint8Array", newUint8Array);
return this.WriteToMsgLenght(newUint8Array);
}
/**
* 写入消息长度
* 1.uint8Array-原数组
*/
WriteToMsgLenght(uint8Array: Uint8Array): Uint8Array {
let newUint8Array: Uint8Array = new Uint8Array(uint8Array.length + 4);
let arrayBuffer = new ArrayBuffer(4);
var dv = new DataView(arrayBuffer);
dv.setInt32(0, uint8Array.length, true);
let uint8Array0 = new Uint8Array(arrayBuffer);
newUint8Array.set(uint8Array0);
newUint8Array.set(uint8Array, uint8Array0.length);
console.log("写长度newUint8Array", newUint8Array);
return newUint8Array;
}
/**
* 拆包
* 获取到正确长度后直接获取消息类型与实际消息体
*/
DecodePack(arrayBuffer: ArrayBuffer): { msgType: number, data: Uint8Array } {
let readLengthArryBuffer: ArrayBuffer = null;
var dv = new DataView(arrayBuffer);
let length = dv.getInt32(0, true);
readLengthArryBuffer = arrayBuffer.slice(4, arrayBuffer.byteLength);
if (length > readLengthArryBuffer.byteLength) {
console.log("未收到正确消息长度", length, readLengthArryBuffer.byteLength);
}
return this.ReadOfMsgType(readLengthArryBuffer);
}
/**
* 获取消息类型与消息体
*/
ReadOfMsgType(arrayBuffer: ArrayBuffer): { msgType: number, data: Uint8Array } {
let readMsgArryBuffer: ArrayBuffer = null;
var dv = new DataView(arrayBuffer);
let mt = dv.getUint16(0, true);
readMsgArryBuffer = arrayBuffer.slice(2, arrayBuffer.byteLength);
console.log("消息体", length, readMsgArryBuffer.byteLength);
return { msgType: mt, data: new Uint8Array(readMsgArryBuffer) };
}
}
已经在使用目前没有问题,有需要改进的,欢迎指正
文件下载地址:下载后改为ts后缀
