ts-sdk

packet.ts 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { Utils } from './utils';
  2. import 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(
  12. operator: number,
  13. sequence: number,
  14. header: string,
  15. body: string,
  16. ): ArrayBuffer {
  17. header = Utils.encrypt(header, this.key, this.key);
  18. body = Utils.encrypt(body, this.key, this.key);
  19. const headerLength = header.length;
  20. const bodyLength = body.length;
  21. const buf = new ArrayBuffer(20 + headerLength + bodyLength);
  22. const dataView = new DataView(buf);
  23. const nsBuf = new Int64(sequence).toBuffer();
  24. dataView.setUint32(0, operator);
  25. dataView.setUint32(12, headerLength);
  26. dataView.setUint32(16, bodyLength);
  27. let bufView = new Uint8Array(buf);
  28. for (var i = 0; i < 8; i++) {
  29. bufView[4 + i] = nsBuf[i];
  30. }
  31. for (let i = 0; i < headerLength; i++) {
  32. bufView[20 + i] = header.charCodeAt(i);
  33. }
  34. for (let i = 0; i < bodyLength; i++) {
  35. bufView[20 + headerLength + i] = body.charCodeAt(i);
  36. }
  37. return buf;
  38. }
  39. public unPack(data: ArrayBuffer | SharedArrayBuffer): Packet {
  40. const dataView = new DataView(data);
  41. this.operator = dataView.getUint32(0, false);
  42. this.sequence = new Int64(
  43. new Uint8Array(dataView.buffer.slice(4, 12)),
  44. ).toNumber();
  45. this.headerLength = dataView.getUint32(12, false);
  46. this.bodyLength = dataView.getUint32(16, false);
  47. const header = Utils.ab2str(
  48. dataView.buffer.slice(20, 20 + this.headerLength),
  49. );
  50. const body = Utils.ab2str(dataView.buffer.slice(20 + this.headerLength));
  51. this.header = Utils.decrypt(header, this.key, this.key);
  52. this.body = Utils.decrypt(body, this.key, this.key);
  53. return this;
  54. }
  55. }