首页 > 解决方案 > 将节点 TCP 流分成数据包的最佳实践?

问题描述

我正在使用 Node 的 TCP 客户端作为我的游戏的实时后端,它以固定长度的协议进行通信。例如,

0x00 - Connection Request
int32 Identifier
4 bytes long

0x01 - Position Update
int32 positionx
int32 positiony
8 bytes long

当然,Node 是这样工作的

socket.on("data", (data) => {
   // Arbitary buffer of bytes
})

我只想在收到完整的数据包后一次处理一个数据包,但是最好的方法是A:继续添加到缓冲区直到收到完整的数据包,并且B:确保不包含 a 的数据第一个中的第二个数据包

标签: node.jsnetworkingtcp

解决方案


我就是这样解决的!

function readData(data, socket) {
    console.log("Read chunk of data " + data.length + " bytes long")

    while (data.length > 0) {
        if (expectsNewPacket) {
            packetBuffer = new Buffer(0)
            currentPacketInfo = getPacketInformationFromHeader(data)
            data = currentPacketInfo.slicedData
            console.log("New packet: ident " + currentPacketInfo.ident + ", length: " + currentPacketInfo.length)
            expectedLengthRemaining = currentPacketInfo.length
            expectsNewPacket = false
        }


        // If the data is more than the rest of the packet, just concat the rest of the packet and remove it from our block
        if (data.length >= expectedLengthRemaining) {
            packetBuffer = Buffer.concat([packetBuffer, data.slice(0, expectedLengthRemaining)]) 
            data = data.slice(expectedLengthRemaining)

            processPacket(packetBuffer, socket)
            expectsNewPacket = true
        } else {
            // Or if the data length is less than what we need, just add all that we can and we'll add more later
            packetBuffer = Buffer.concat([packetBuffer, data.slice(0, data.length)])
            data = data.slice(data.length)
        }
    }
}

推荐阅读