![](/img/trans.png)
[英]Node.js with Socket.io - Long Polling fails and throws “code”:1,“message”:“Session ID unknown” response
[英]How long is the message boundary in node.js?
如何在node.js中檢測消息邊界? 客戶端發送消息的長度為: length + data
。
socket.on(data)
在一行中接收所有數據。 但是,我只需要先接收2個字節,然后再接收x
個字節的數據。
tcp套接字只是字節流,沒有消息邊界,您需要計算消耗的字節並將此數字與前導中的字節進行比較。
這里有一些代碼可以滿足您的需求。 它是用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.