-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathJson.ts
38 lines (32 loc) · 1.13 KB
/
Json.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { BufferedConnection } from "./BufferedConnection";
import { DataConnectionErrorType, SerializationType } from "../../enums";
import { util } from "../../util";
export class Json extends BufferedConnection {
readonly serialization = SerializationType.JSON;
private readonly encoder = new TextEncoder();
private readonly decoder = new TextDecoder();
stringify: (data: any) => string = JSON.stringify;
parse: (data: string) => any = JSON.parse;
// Handles a DataChannel message.
protected override _handleDataMessage({ data }: { data: Uint8Array }): void {
const deserializedData = this.parse(this.decoder.decode(data));
// PeerJS specific message
const peerData = deserializedData["__peerData"];
if (peerData && peerData.type === "close") {
this.close();
return;
}
this.emit("data", deserializedData);
}
override _send(data, _chunked) {
const encodedData = this.encoder.encode(this.stringify(data));
if (encodedData.byteLength >= util.chunkedMTU) {
this.emitError(
DataConnectionErrorType.MessageToBig,
"Message too big for JSON channel",
);
return;
}
this._bufferedSend(encodedData);
}
}