[英]Socket.io - limit connections per IP address
有沒有辦法限制從同一 IP 地址到 socket.io 服務器的連接數? 例如,我可以將限制設置為 3,然后當有人打開 4 個選項卡加入服務器時,其中三個會連接,而第四個或之后的任何一個都無法連接。
我不是要限制連接總數,只是為了一個人。
這樣做的最佳方法是什么?
當然,如果用戶有 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).
}
// 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++;
});
如果您在 Socket 服務器上使用 Node.js,我建議您像這樣獲取 IP:
var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.