lengthFieldDecoder.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /** 消息头和数据长度一起发送的解码器 */
  2. class lengthFieldDecoder{
  3. /** 消息头字节长度 */
  4. headerLength;
  5. /** 完整数据包处理 */
  6. completeDataExecute;
  7. /** 传入的数据 */
  8. chunks = [];
  9. /** 记录buffer最大长度 字节数byte */
  10. maxSize = 0;
  11. constructor(headerLength,maxSize,completeDataExecute) {
  12. this.headerLength = headerLength;
  13. this.maxSize = maxSize;
  14. this.completeDataExecute = completeDataExecute;
  15. }
  16. /**
  17. * 接收数据
  18. * @param data
  19. */
  20. read(data){
  21. if(this.chunks.length === 0){
  22. this.chunks = data;
  23. }else{
  24. this.chunks = Buffer.concat([this.chunks,data]);
  25. }
  26. while(true){
  27. if(this.chunks.length < this.headerLength){
  28. break;
  29. }
  30. let headerBytes = this.chunks.slice(0,this.headerLength);
  31. // 实际传输的消息长度
  32. let dataLength = this.buildDataLengthFromHeader(headerBytes);
  33. let totalLength = this.headerLength + dataLength;
  34. if(this.chunks.length < totalLength){
  35. break;
  36. }
  37. let completeData = this.chunks.slice(this.headerLength,totalLength);
  38. this.chunks = this.chunks.slice(totalLength);
  39. this.completeDataExecute(completeData);
  40. }
  41. }
  42. /**
  43. * header字节数据转为十进制的数
  44. * @param headerBytes
  45. * @returns {number}
  46. */
  47. buildDataLengthFromHeader(headerBytes){
  48. let binaryStr = "";
  49. for(let i = 0 ;i< this.headerLength; i++){
  50. let cStr = headerBytes[i].toString(2);
  51. let originalCStr = cStr.length;
  52. for(let j=0;j<8-originalCStr;j++){
  53. cStr = "0" + cStr;
  54. }
  55. binaryStr = binaryStr + cStr;
  56. }
  57. return parseInt(binaryStr,2);
  58. }
  59. }
  60. module.exports = lengthFieldDecoder;