lengthFieldEncoder.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /** 消息头和数据长度一起发送的编码器 */
  2. class lengthFieldEncoder{
  3. /** 消息头字节长度 */
  4. headerLength;
  5. /** 记录buffer最大长度 字节数byte */
  6. maxSize = 0;
  7. constructor(headerLength,maxSize) {
  8. this.headerLength = headerLength;
  9. this.maxSize = maxSize;
  10. }
  11. /** 编码 data 必须是byte数组 */
  12. encode(data){
  13. if(data.length > this.maxSize){
  14. throw new Error("数据超过编码最大长度");
  15. }
  16. let headerBytes = this.buildDataLengthBytes(data.length);
  17. let headerBuffer = Buffer.from(headerBytes);
  18. return Buffer.concat([headerBuffer,data]);
  19. }
  20. /**
  21. * 构建头部的字节数组数据
  22. * @param dataLength
  23. * @returns {[]}
  24. */
  25. buildDataLengthBytes(dataLength){
  26. let headerBytes = [];
  27. let binaryStr = dataLength.toString(2);
  28. let originalLength = binaryStr.length;
  29. for(let i = 0;i< this.headerLength*8 - originalLength ;i++){
  30. binaryStr = "0"+binaryStr;
  31. }
  32. for(let i = 0;i< this.headerLength ;i++){
  33. headerBytes.push(parseInt(binaryStr.substring((i*8),(i*8 + 8)),2));
  34. }
  35. return headerBytes;
  36. }
  37. }
  38. module.exports = lengthFieldEncoder;