TCPAbridged.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { readBufferFromBigInt } from "../../Helpers";
  2. import { Connection, PacketCodec } from "./Connection";
  3. import type { PromisedNetSockets, PromisedWebSockets } from "../../extensions";
  4. import bigInt from "big-integer";
  5. export class AbridgedPacketCodec extends PacketCodec {
  6. static tag = Buffer.from("ef", "hex");
  7. static obfuscateTag = Buffer.from("efefefef", "hex");
  8. private tag: Buffer;
  9. private obfuscateTag: Buffer;
  10. constructor(props: any) {
  11. super(props);
  12. this.tag = AbridgedPacketCodec.tag;
  13. this.obfuscateTag = AbridgedPacketCodec.obfuscateTag;
  14. }
  15. encodePacket(data: Buffer) {
  16. let length = data.length >> 2;
  17. let temp;
  18. if (length < 127) {
  19. const b = Buffer.alloc(1);
  20. b.writeUInt8(length, 0);
  21. temp = b;
  22. } else {
  23. temp = Buffer.concat([
  24. Buffer.from("7f", "hex"),
  25. readBufferFromBigInt(bigInt(length), 3),
  26. ]);
  27. }
  28. return Buffer.concat([temp, data]);
  29. }
  30. async readPacket(
  31. reader: PromisedNetSockets | PromisedWebSockets
  32. ): Promise<Buffer> {
  33. const readData = await reader.read(1);
  34. let length = readData[0];
  35. if (length >= 127) {
  36. length = Buffer.concat([
  37. await reader.read(3),
  38. Buffer.alloc(1),
  39. ]).readInt32LE(0);
  40. }
  41. return reader.read(length << 2);
  42. }
  43. }
  44. /**
  45. * This is the mode with the lowest overhead, as it will
  46. * only require 1 byte if the packet length is less than
  47. * 508 bytes (127 << 2, which is very common).
  48. */
  49. export class ConnectionTCPAbridged extends Connection {
  50. PacketCodecClass = AbridgedPacketCodec;
  51. }