- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我怎样才能阻止某人简单地做
while(true){client.emit('i am spammer', true)};
当有人想要让我的 Node 服务器崩溃时,这肯定是个问题!
最佳答案
就像 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/
元素?
我有一个 Linux 机器,我注意到每当我运行 adb 时,大量垃圾消息就会涌入系统日志,例如: Mar 09 17:22:39 laptoo kernel: hub 1-0:1.0: hub_res
我正在制作一个简单的命令行程序,用于使用 Python 中的 Twill 模块从网站(非常通用)收集和解析信息。我想使用 Twill 的 show() 命令将 HTML 输出分配给一个变量,以通过我的
我最近编写了一个处理大量吞吐量(每天 60+ 百万个请求)的小型服务,但它遇到了内存问题。起初,我查看了所有常见的嫌疑人,确信它必须是我写的东西,而不是与非常有用的、面向性能的 ServiceStac
使用 nvcc(使用 cuda 3.1)编译项目时,我从 gthr-default.h 收到大量警告: /usr/lib/gcc/x86_64-redhat-linux/4.4.4/../../../
我是一名优秀的程序员,十分优秀!