Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. const shortId = require('shortid');
  2. const {CRC} = require('crc-full');
  3.  
  4. const MTU = 22;
  5. const HEAD_LENGTH = 21;
  6. const PAYLOAD_LENGTH = MTU - HEAD_LENGTH;
  7. const FLAG = 255;
  8. const FLAG_BIT = new Uint8Array([255]);
  9.  
  10. const crc = new CRC('CRC8', 8, 0x07, 0x00, 0x00, false, false);
  11.  
  12. function sendData(data) {
  13. let chunkSize = Math.ceil(data.length / PAYLOAD_LENGTH)
  14. let cs = chunkSize.toString(32).padStart(2);
  15. let id = shortId().padStart(13);
  16. let chunks = [];
  17.  
  18. for (let offset = 0; offset < chunkSize; offset++) {
  19. let co = (offset + 1).toString(32).padStart(2);
  20. let chunk = Buffer.concat([
  21. Buffer.from(`${co}${cs}${id} `),
  22. data.slice(offset, PAYLOAD_LENGTH + (PAYLOAD_LENGTH * offset))
  23. ]);
  24. let crcCode = crc.compute(chunk).toString(32).padStart(2);
  25.  
  26. chunk = Buffer.concat([
  27. FLAG_BIT,
  28. Buffer.from(crcCode),
  29. chunk
  30. ]);
  31.  
  32. chunks.push(chunk);
  33. }
  34.  
  35. chunks.map(chunk => {
  36. console.log(chunk.toString())
  37. });
  38.  
  39. return chunks;
  40. }
  41.  
  42. let map = new Map();
  43.  
  44. function recvData(data) {
  45. let x = data[0];
  46.  
  47. if (x !== FLAG) {
  48. return;
  49. }
  50.  
  51. let crcCode = parseInt(data.slice(1, 3), 32);
  52.  
  53. if (isNaN(crcCode)) {
  54. return;
  55. }
  56.  
  57. let content = data.slice(3);
  58.  
  59. if (crc.compute(content) !== crcCode) {
  60. return;
  61. }
  62.  
  63. let offset = parseInt(content.slice(0, 2), 32);
  64. let chunkSize = parseInt(content.slice(2, 4), 32);
  65. let id =content.slice(4, 17).toString().trim();
  66. let body = content.slice(18);
  67.  
  68. let cache = map.get(id) || {length: 0};
  69.  
  70. let index = offset - 1;
  71.  
  72. if (!cache[index]) {
  73. cache.length++;
  74. }
  75.  
  76. cache[offset - 1] = body;
  77.  
  78. if (cache.length === chunkSize) {
  79. console.log(Buffer.concat(Array.from(cache)).toString());
  80. map.delete(id);
  81. } else {
  82. map.set(id, cache)
  83. }
  84. }
  85.  
  86. let chunks = sendData(Buffer.from('hello!'));
  87.  
  88. console.log('----')
  89.  
  90. for (let chunk of chunks) {
  91. recvData(chunk);
  92. }
  93.  
  94. console.log('----');
  95.  
  96. for (let chunk of chunks.reverse()) {
  97. recvData(chunk);
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement