将Node TCP流分离为数据包的最佳实践?

时间:2018-07-09 00:26:54

标签: node.js networking 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的最佳方法是什么:继续添加到缓冲区中直到收到完整的数据包和< em> B:确保在第一个数据包中不包含第二个数据包的数据

1 个答案:

答案 0 :(得分:0)

这就是我解决的方法!

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)
        }
    }
}