节点socket.io,什么防止洪水?

Jus*_*tin 8 node.js socket.io

我怎样才能阻止某人干脆做

while(true){client.emit('i am spammer', true)};
Run Code Online (Sandbox Code Playgroud)

当有人有崩溃我的节点服务器的冲动时,这确实是一个问题!

在此输入图像描述

dot*_*ack 5

就像 tsrurzl 所说的,你需要实现一个速率限制器(节流套接字)。

以下代码示例仅在您的套接字返回 Buffer (而不是字符串)时可靠地工作。该代码示例假定您将首先调用 addRatingEntry(),然后立即调用 evalRating()。否则,在根本没有调用 evalRating() 或太晚的情况下,您将面临内存泄漏的风险。

var rating, limit, interval;

rating = []; // rating: [*{'timestamp', 'size'}]
limit = 1048576; // limit: maximum number of bytes/characters.
interval = 1000; // interval: interval in milliseconds.
// Describes a rate limit of 1mb/s

function addRatingEntry (size) {
    // Returns entry object.
    return rating[(rating.push({
        'timestamp': Date.now(),
        'size': size
    }) - 1);
}

function evalRating () {
// Removes outdated entries, computes combined size, and compares with limit variable.
// Returns true if you're connection is NOT flooding, returns false if you need to disconnect.
    var i, newRating, totalSize;
    // totalSize in bytes in case of underlying Buffer value, in number of characters for strings. Actual byte size in case of strings might be variable => not reliable.
    newRating = [];
    for (i = rating.length - 1; i >= 0; i -= 1) {
        if ((Date.now() - rating[i].timestamp) < interval) {
            newRating.push(rating[i]);
        }
    }
    rating = newRating;

    totalSize = 0;
    for (i = newRating.length - 1; i >= 0; i -= 1) {
        totalSize += newRating[i].timestamp;
    }

    return (totalSize > limit ? false : true);
}

// Assume connection variable already exists and has a readable stream interface
connection.on('data', function (chunk) {
    addRatingEntry(chunk.length);
    if (evalRating()) {
         // Continue processing chunk.
    } else {
         // Disconnect due to flooding.
    }
});
Run Code Online (Sandbox Code Playgroud)

您可以添加额外的检查,例如检查 size 参数是否真的是数字等。

附录:确保每个连接都包含评级、限制和间隔变量(在闭包中),并且它们没有定义全局速率(其中每个连接操作相同的评级)。