No Description

packet.ts 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { Utils } from './utils';
  2. import * as Int64 from 'node-int64';
  3. export class Packet {
  4. private key: string = 'b8ca9aa66def05ff3f24919274bb4a66';
  5. public operator: number;
  6. public sequence: number;
  7. public headerLength: number;
  8. public bodyLength: number;
  9. public header: string;
  10. public body: string;
  11. public pack(operator: number, sequence: number, header: string, body: string): ArrayBuffer {
  12. header = Utils.encrypt(header, this.key, this.key);
  13. body = Utils.encrypt(body, this.key, this.key);
  14. const headerLength = header.length;
  15. const bodyLength = body.length;
  16. const buf = new ArrayBuffer(20 + headerLength + bodyLength);
  17. const dataView = new DataView(buf);
  18. const nsBuf = new Int64(sequence).toBuffer();
  19. dataView.setUint32(0, operator);
  20. dataView.setUint32(12, headerLength);
  21. dataView.setUint32(16, bodyLength);
  22. let bufView = new Uint8Array(buf);
  23. for (var i = 0; i < 8; i++) {
  24. bufView[4 + i] = nsBuf[i];
  25. }
  26. for (let i = 0; i < headerLength; i++) {
  27. bufView[20 + i] = header.charCodeAt(i);
  28. }
  29. for (let i = 0; i < bodyLength; i++) {
  30. bufView[20 + headerLength + i] = body.charCodeAt(i);
  31. }
  32. return buf;
  33. }
  34. public unPack(data: ArrayBuffer | SharedArrayBuffer): Packet {
  35. const dataView = new DataView(data);
  36. this.operator = dataView.getUint32(0, false);
  37. this.sequence = new Int64(new Uint8Array(dataView.buffer.slice(4, 12))).toNumber();
  38. this.headerLength = dataView.getUint32(12, false);
  39. this.bodyLength = dataView.getUint32(16, false);
  40. const header = Utils.ab2str(dataView.buffer.slice(20, 20 + this.headerLength));
  41. const body = Utils.ab2str(dataView.buffer.slice(20 + this.headerLength));
  42. this.header = Utils.decrypt(header, this.key, this.key);
  43. this.body = Utils.decrypt(body, this.key, this.key);
  44. return this;
  45. }
  46. }