MsgPack.ts 710 B

123456789101112131415161718192021222324252627
  1. import { decodeMultiStream, Encoder } from "@msgpack/msgpack";
  2. import { StreamConnection } from "./StreamConnection.js";
  3. import type { Peer } from "../../peer.js";
  4. export class MsgPack extends StreamConnection {
  5. readonly serialization = "MsgPack";
  6. private _encoder = new Encoder();
  7. constructor(peerId: string, provider: Peer, options: any) {
  8. super(peerId, provider, options);
  9. (async () => {
  10. for await (const msg of decodeMultiStream(this._rawReadStream)) {
  11. // @ts-ignore
  12. if (msg.__peerData?.type === "close") {
  13. this.close();
  14. return;
  15. }
  16. this.emit("data", msg);
  17. }
  18. })();
  19. }
  20. protected override _send(data) {
  21. return this.writer.write(this._encoder.encode(data));
  22. }
  23. }