gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:16 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com