32
33
constructor() {
35
>
}
36
37
protected connect(readable: stream.Readable, writable: stream.Writable): void {
39
>
this.outputStream = writable;
40
>
this.rawData = Buffer.allocUnsafe(0);
41
>
this.contentLength = -1;
42
>
43
>
readable.on('data', (data: Buffer) => this.handleData(data));
44
>
}
45
46
sendMessage(message: DebugProtocol.ProtocolMessage): void {
48
>
if (this.outputStream) {
49
>
const json = JSON.stringify(message);
50
>
this.outputStream.write(`Content-Length: ${Buffer.byteLength(json, 'utf8')}${StreamDebugAdapter.TWO_CRLF}${json}`, 'utf8');
51
>
}
52
>
}
53
54
private handleData(data: Buffer): void {
56
>
this.rawData = Buffer.concat([this.rawData, data]);
57
>
58
>
while (true) {
59
>
if (this.contentLength >= 0) {
60
>
if (this.rawData.length >= this.contentLength) {
61
>
const message = this.rawData.toString('utf8', 0, this.contentLength);
62
>
this.rawData = this.rawData.slice(this.contentLength);
63
>
this.contentLength = -1;
64
>
if (message.length > 0) {
65
>
try {
66
>
this.acceptMessage(<DebugProtocol.ProtocolMessage>JSON.parse(message));
67
>
} catch (e) {
68
this._onError.fire(new Error((e.message || e) + '\n' + message));
69
}
71
>
continue; // there may be more complete messages to process
72
>
}
73
>
} else {
74
>
const idx = this.rawData.indexOf(StreamDebugAdapter.TWO_CRLF);
75
>
if (idx !== -1) {
76
>
const header = this.rawData.toString('utf8', 0, idx);
77
>
const lines = header.split(StreamDebugAdapter.HEADER_LINESEPARATOR);
78
>
for (const h of lines) {
79
>
const kvPair = h.split(StreamDebugAdapter.HEADER_FIELDSEPARATOR);
80
>
if (kvPair[0] === 'Content-Length') {
81
>
this.contentLength = Number(kvPair[1]);
82
>
}
83
>
}
84
>
this.rawData = this.rawData.slice(idx + StreamDebugAdapter.TWO_CRLF.length);
85
>
continue;
86
>
}
87
>
}
88
>
break;
89
>
}
90
>
}
91
}
92