How can I detect the message boundary in node.js? The client sends messages with along their length: length + data
.
socket.on(data)
receives all data in one line. But, I need to receive only 2 bytes first then x
bytes data.
tcp sockets are just byte streams, there's no message boundary, you need to count the bytes consumed and compare this number to the one from the preamble.
here's a bit of code that does what you need. it's written in CoffeeScript, and uses 32-bit int for message size, so you'll have to adjust a bit.
remaining = 0
input = undefined
msgsize = 0
msbuf = new Buffer 4
msneeded = 4
sock.on 'data', (bytes) =>
start = 0
end = bytes.length
while start < bytes.length
if remaining == 0
msavail = (Math.min 4, bytes.length - start)
bytes.copy msbuf, msbuf.length - msneeded, start, start + msavail
msneeded -= msavail
continue if msneeded > 0
msneeded = 4
remaining = msgsize = msbuf.readUInt32LE 0
start += 4
input = new Buffer msgsize
end = (Math.min start + remaining, bytes.length)
bytes.copy input, msgsize - remaining, start, end
remaining -= (end - start)
start = end
@emit 'data', input if 0 == remaining
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.