![](/img/trans.png)
[英]Secure WebSocket Connection through nginx 1.10.3 and LetsEncrypt
[英]Rate limiting single websocket connection with nginx
我正在尝试为单个websocket连接设置速率限制(这样,最终用户就不会用setInterval(_=>socket.send(1))
或类似的东西轰炸连接)。
我使用NodeJS作为后端,使用nginx作为反向代理。 当然,我可以检查节点上的websocket轰炸,但我在考虑nginx是否可以处理此负载,因为它将使节点免于执行其他任务。 我找不到有关使用nginx限制单个websocket连接的任何信息。 可能吗?
因为没有答案,所以这里不是NGINX解决方案。
速率限制器灵活的软件包有帮助。
const app = require('http').createServer();
const io = require('socket.io')(app);
const { RateLimiterMemory } = require('rate-limiter-flexible');
app.listen(3000);
const rateLimiter = new RateLimiterMemory(
{
points: 5, // 5 points
duration: 1, // per second
});
io.on('connection', (socket) => {
socket.on('bcast', async (data) => {
try {
await rateLimiter.consume(socket.handshake.address); // consume 1 point per event from IP
socket.emit('news', { 'data': data });
socket.broadcast.emit('news', { 'data': data });
} catch(rejRes) {
// no available points to consume
// emit error or warning message
socket.emit('blocked', { 'retry-ms': rejRes.msBeforeNext });
}
});
});
在官方文档中阅读更多内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.