Christian Strang
Christian Strang

Reputation: 8530

Socket.io - io.sockets.clients().length how to get unique list of connected clients

I use socket.io to open a socket from my client to my node.js server. I also push the number of connected users to all clients every 10 seconds using io.sockets.clients().length, the problem with this value is, that it doesn't check if the same user has opened multiple tabs with the same page.

Is there a way to get a list of unique clients that are connected in socket.io?

Upvotes: 0

Views: 1752

Answers (2)

exebook
exebook

Reputation: 33980

I suggest you use a browser cookies.

Here is the example:

How do I create and read a value from cookie?

Upvotes: 1

user3030064
user3030064

Reputation: 16

I thing you are locking unique ID for each person.

Client code.

//When user connect to socket server to emit some info event like this socket.emit('userInfo','clintUniqueID');//like mailid ID,username,anything but its unique

//When user open other tabs

socket.on('multipleTabs',function(data){
    //Your operation for client side    
     //example 
      alert('you are open multiple tabs');});

Server code:

var connection={}; //socket.io connection each user 
var usersList=[];//This list only contain unique ID for each connection
socket.on('userInfo',function(data){//emit by client (user)
 connection[socket.id]=socket; // just for connection
 var(var i=0;i<usersList.length;i++)
     {
           if(usersList[i]==data)//Here you store user unique ID like mailID,Username etc
             {
                  //user open multiple tabs  
                  //Any operation server site
                  //if you want to do any operation in  client site
                    socket.emit('multipleTabs','userAlreadyExit');



       }else
           {
                        if(i==usersList.length-1)
                           {
                               usersList.push(data);//store socket.id 
                                  }

                     }
 });

Now it will work check it

Upvotes: 0

Related Questions