Json.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { BufferedConnection } from "./BufferedConnection";
  2. import { DataConnectionErrorType, SerializationType } from "../../enums";
  3. import { util } from "../../util";
  4. export class Json extends BufferedConnection {
  5. readonly serialization = SerializationType.JSON;
  6. private readonly encoder = new TextEncoder();
  7. private readonly decoder = new TextDecoder();
  8. stringify: (data: any) => string = JSON.stringify;
  9. parse: (data: string) => any = JSON.parse;
  10. // Handles a DataChannel message.
  11. protected override _handleDataMessage({ data }: { data: Uint8Array }): void {
  12. const deserializedData = this.parse(this.decoder.decode(data));
  13. // PeerJS specific message
  14. const peerData = deserializedData["__peerData"];
  15. if (peerData && peerData.type === "close") {
  16. this.close();
  17. return;
  18. }
  19. this.emit("data", deserializedData);
  20. }
  21. override _send(data, _chunked) {
  22. const encodedData = this.encoder.encode(this.stringify(data));
  23. if (encodedData.byteLength >= util.chunkedMTU) {
  24. this.emitError(
  25. DataConnectionErrorType.MessageToBig,
  26. "Message too big for JSON channel",
  27. );
  28. return;
  29. }
  30. this._bufferedSend(encodedData);
  31. }
  32. }