[英]How long is the message boundary in node.js?
How can I detect the message boundary in node.js? 如何在node.js中检测消息边界? The client sends messages with along their length:
length + data
. 客户端发送消息的长度为:
length + data
。
socket.on(data)
receives all data in one line. socket.on(data)
在一行中接收所有数据。 But, I need to receive only 2 bytes first then x
bytes data. 但是,我只需要先接收2个字节,然后再接收
x
个字节的数据。
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. tcp套接字只是字节流,没有消息边界,您需要计算消耗的字节并将此数字与前导中的字节进行比较。
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.
它是用CoffeeScript编写的,并且使用32位int表示消息大小,因此您必须进行一些调整。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.