node.js - Node socket.io,有什么可以防止泛滥的吗?

标签 node.js socket.io

我怎样才能阻止某人简单地做

while(true){client.emit('i am spammer', true)};

当有人想要让我的 Node 服务器崩溃时,这肯定是个问题!

enter image description here

最佳答案

就像 tsrurzl 说的,你需要实现一个 rate limiter (节流套接字)。

以下代码示例仅在您的套接字返回 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.
    }
});

你可以添加额外的检查,比如检查大小参数是否真的是一个数字等。

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

关于node.js - Node socket.io,有什么可以防止泛滥的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22110010/

相关文章:

windows - 离线安装socket.io

javascript - 有什么方法可以使用 Node JS 流式传输照片?

javascript - io.sockets.emit 有效但 io.sockets.on 无效

javascript - AWS 从客户端上传文件到 S3

javascript - 将mysql查询返回到nodejs flash消息

node.js - 类型错误 : next is not a function when io. 使用(passport.authenticate ('google' ))

node.js - Socket.io 命名空间上的重复客户端

mysql - Node.js promise 和错误处理。这不能做得更干净吗?

javascript - react : Update component data/props after promise resolved

node.js - 如何将 socket.io 与 webpack-hot-middleware 一起使用?