简体   繁体   English

Socket.io - 限制每个 IP 地址的连接数

[英]Socket.io - limit connections per IP address

Is there a way to limit the number of connections to a socket.io server from the same IP address?有没有办法限制从同一 IP 地址到 socket.io 服务器的连接数? For example, I could set the limit to 3, and then when someone opened 4 tabs to join the server, three of them would connect and the fourth or any after wouldn't get connected.例如,我可以将限制设置为 3,然后当有人打开 4 个选项卡加入服务器时,其中三个会连接,而第四个或之后的任何一个都无法连接。

I'm not trying to cap the number of connections total, just for one person.我不是要限制连接总数,只是为了一个人。

What's the best way of doing this?这样做的最佳方法是什么?

Of course, if the user had VPN, the IP address would be disabled.当然,如果用户有 VPN,IP 地址将被禁用。 But still, there might be another way of doing this.但是,可能还有另一种方法可以做到这一点。

> One: Every time a user joins the page, give them an id, and store it in a variable server-side. > 一:用户每次加入页面时,给他们一个id,并将其存储在服务器端的变量中。

socket.on('connection', () => { users++ });

which will add the number of users connected.这将添加连接的用户数。
> Two: Create a unique ID and cancel the " users++ " so the user doesn't get counted again. > 二:创建一个唯一的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).
}
// 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++;
});

If you're using Node.js for your Socket server, I recommend getting the IP like this:如果您在 Socket 服务器上使用 Node.js,我建议您像这样获取 IP:

var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM