Node.js net tcp缓冲内存泄漏

时间:2015-04-05 20:39:26

标签: javascript node.js memory-leaks tcp buffer

我在Node.js中编写了一个TCP游戏服务器,并且遇到了将TCP流拆分成消息的问题。因为我想从缓冲区中读取数字和浮点数,所以我找不到合适的模块来外包,因为我发现所有的模块都处理以新行分隔符结尾的简单字符串。我决定使用消息的长度(以字节为单位)为每条消息添加前缀。我做了这个并编写了一个简单的程序,用随机消息向服务器发送垃圾邮件(用一个描述消息长度的UInt16LE前缀构造)。我注意到,我离开运行我的实际服务器的程序的时间越长,内存越来越多。我尝试使用调试工具跟踪内存分配没有成功,所以我想我在这里发布我的代码并希望得到回复。所以这是我的代码......关于我出错的地方或者我可以做的不同/更有效的任何提示或指示将是惊人的! 感谢。

server.on("connection", function(socket) {
var session = new sessionCS(socket);
console.log("Connection from " + session.address);

// data buffering variables
var currentBuffer = new Buffer(args.bufSize);
var bufWrite = 0;
var bufRead = 0;
var mSize = null;
var i = 0;

socket.on("data", function(dataBuffer) {

    // check if buffer risk of overflow
    if (bufWrite + dataBuffer.length > args.bufSize-1) {
        var newBufWrite = 0;
        var newBuffer = new Buffer(args.bufSize);

        while(bufRead < bufWrite) {
            newBuffer[newBufWrite] = currentBuffer[bufRead];
            newBufWrite++;
            bufRead++;
        }

        currentBuffer = newBuffer;
        bufWrite = newBufWrite;
        bufRead = 0;
        newBufWrite = null;
    }

    // appending buffer
    for (i=0; i<dataBuffer.length; i++) {
        currentBuffer[bufWrite] = dataBuffer[i];
        bufWrite ++;
    }

    // if beginning of message not acknowleged
    if (mSize === null && (bufWrite - bufRead) >= 2) {
        mSize = currentBuffer.readUInt16LE(bufRead);
    }

    // if difference between read and write is greater or equal to message mSize + 2
    // +2 for the integer holding the message size
    // this means that a full message is in the buffer and needs to be extracted
    while ((bufWrite - bufRead) >= mSize+2) {
        bufRead += 2;
        var messageBuffer = new Buffer(mSize);

        for(i=0; i<messageBuffer.length; i++) {
            messageBuffer[i] = currentBuffer[bufRead];
            bufRead++;
        }

        // this is where the message buffer would be passed to the router
        router(session, messageBuffer);
        messageBuffer = null;

        // seeinf if another message length indicator is in the buffer
        if ((bufWrite - bufRead) >= 2) {
            mSize = currentBuffer.readUInt16LE(bufRead);
        }
        else {
            mSize = null;
        }
    }
});
}

1 个答案:

答案 0 :(得分:0)

缓冲帧序列化协议(BUFSP)https://github.com/teambition/bufsp 您可能需要:将消息编码到缓冲区,写入TCP,接收TCP流缓冲区并将其拆分为消息。