From 2662484028547f18b79874733fabe7a1fab1028d Mon Sep 17 00:00:00 2001 From: Shinya Kasatani Date: Thu, 13 Jan 2022 22:02:35 +0900 Subject: [PATCH] fix missing messages when multiple messages are read at once --- protocol.js | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/protocol.js b/protocol.js index 91662a3..96f1ffa 100644 --- a/protocol.js +++ b/protocol.js @@ -1,21 +1,26 @@ +var input = Buffer.from([]); module.exports = (handleMessage) => { process.stdin.on('readable', () => { - var input = [] - var chunk + var chunks = [input]; + var chunk; while (chunk = process.stdin.read()) { - input.push(chunk) + chunks.push(chunk) } - input = Buffer.concat(input) - - var msgLen = input.readUInt32LE(0) - var dataLen = msgLen + 4 - - if (input.length >= dataLen) { - var content = input.slice(4, dataLen) - var json = JSON.parse(content.toString()) - handleMessage(json) + input = Buffer.concat(chunks) + while (input.length >= 4) { + var msgLen = input.readUInt32LE(0) + var dataLen = msgLen + 4 + + if (input.length >= dataLen) { + var content = input.slice(4, dataLen) + var json = JSON.parse(content.toString()) + handleMessage(json) + input = input.slice(dataLen); + } else { + break; + } } })