UNPKG

2.62 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.JsonSocket = void 0;
4const buffer_1 = require("buffer");
5const string_decoder_1 = require("string_decoder");
6const corrupted_packet_length_exception_1 = require("../errors/corrupted-packet-length.exception");
7const tcp_socket_1 = require("./tcp-socket");
8class JsonSocket extends tcp_socket_1.TcpSocket {
9 constructor() {
10 super(...arguments);
11 this.contentLength = null;
12 this.buffer = '';
13 this.stringDecoder = new string_decoder_1.StringDecoder();
14 this.delimiter = '#';
15 }
16 handleSend(message, callback) {
17 this.socket.write(this.formatMessageData(message), 'utf-8', callback);
18 }
19 handleData(dataRaw) {
20 const data = buffer_1.Buffer.isBuffer(dataRaw)
21 ? this.stringDecoder.write(dataRaw)
22 : dataRaw;
23 this.buffer += data;
24 if (this.contentLength == null) {
25 const i = this.buffer.indexOf(this.delimiter);
26 /**
27 * Check if the buffer has the delimiter (#),
28 * if not, the end of the buffer string might be in the middle of a content length string
29 */
30 if (i !== -1) {
31 const rawContentLength = this.buffer.substring(0, i);
32 this.contentLength = parseInt(rawContentLength, 10);
33 if (isNaN(this.contentLength)) {
34 this.contentLength = null;
35 this.buffer = '';
36 throw new corrupted_packet_length_exception_1.CorruptedPacketLengthException(rawContentLength);
37 }
38 this.buffer = this.buffer.substring(i + 1);
39 }
40 }
41 if (this.contentLength !== null) {
42 const length = this.buffer.length;
43 if (length === this.contentLength) {
44 this.handleMessage(this.buffer);
45 }
46 else if (length > this.contentLength) {
47 const message = this.buffer.substring(0, this.contentLength);
48 const rest = this.buffer.substring(this.contentLength);
49 this.handleMessage(message);
50 this.handleData(rest);
51 }
52 }
53 }
54 handleMessage(message) {
55 this.contentLength = null;
56 this.buffer = '';
57 this.emitMessage(message);
58 }
59 formatMessageData(message) {
60 const messageData = JSON.stringify(message);
61 const length = messageData.length;
62 const data = length + this.delimiter + messageData;
63 return data;
64 }
65}
66exports.JsonSocket = JsonSocket;