Socket.io - 限制每个 IP 地址的连接数
Socket.io - limit connections per IP address
有没有办法限制从同一 IP 地址到 socket.io 服务器的连接数?
例如,我可以将限制设置为 3,然后当有人打开 4 个选项卡加入服务器时,其中三个会连接,第四个或之后的任何一个都不会连接。
我并不是要限制连接总数,只是针对一个人。
执行此操作的最佳方法是什么?
编辑:服务器 运行 在 node.js 上,客户端在网络浏览器上的 js 中
当然,如果用户有VPN,IP地址将被禁用。但是,可能还有另一种方法可以做到这一点。
>一:每次用户加入页面时,给他们一个id,并将其存储在服务器端的变量中。
socket.on('connection', () => { users++ });
这将添加连接的用户数。
> 二:创建唯一ID并取消“users++
”,这样用户就不会被再次统计。
var users = 0;
var userArray = [];
var ip = /* Get the IP address here */;
socket.on('connection', () => {
if (users >= 3) {
// The max users have arrived. (3 is the amount of users).
// Do what you want to block them here.
}
// Check if the user's IP is equal to one in the array
if (userArray.indexOf(ip) > -1) {
// Cancel adding them to number of users
return;
} else {
// Add IP to the array
userArray.push(ip);
users++;
// Do what you want here.
}
});
如果您使用 Node.js 作为 Socket 服务器,我建议您这样获取 IP:
var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim();
有没有办法限制从同一 IP 地址到 socket.io 服务器的连接数? 例如,我可以将限制设置为 3,然后当有人打开 4 个选项卡加入服务器时,其中三个会连接,第四个或之后的任何一个都不会连接。
我并不是要限制连接总数,只是针对一个人。
执行此操作的最佳方法是什么?
编辑:服务器 运行 在 node.js 上,客户端在网络浏览器上的 js 中
当然,如果用户有VPN,IP地址将被禁用。但是,可能还有另一种方法可以做到这一点。
>一:每次用户加入页面时,给他们一个id,并将其存储在服务器端的变量中。
socket.on('connection', () => { users++ });
这将添加连接的用户数。
> 二:创建唯一ID并取消“users++
”,这样用户就不会被再次统计。
var users = 0;
var userArray = [];
var ip = /* Get the IP address here */;
socket.on('connection', () => {
if (users >= 3) {
// The max users have arrived. (3 is the amount of users).
// Do what you want to block them here.
}
// Check if the user's IP is equal to one in the array
if (userArray.indexOf(ip) > -1) {
// Cancel adding them to number of users
return;
} else {
// Add IP to the array
userArray.push(ip);
users++;
// Do what you want here.
}
});
如果您使用 Node.js 作为 Socket 服务器,我建议您这样获取 IP:
var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim();