Question

Now I'm using express4 and socket.io 0.9 to build online chat room.The problem is I don't want same user join the same room when they open another tab in browser(or other browser).I can get the user session(to visit those room,user must logging in,when they logged,the 'uid' will set into the session).

Was it helpful?

Solution 2

What is clearly your problem ? You have trouble accessing the current users in a room ? If this is that, you can get the sockets from a room like this and then check for your user.

First add a parameter to your first socket to be able to identify later.

socket.sessionid=your_user_session_id;

Then, for every connection, check in the sockets of the room if you have already a socket with this session ID

var socketsOfTheRoom = io.sockets.clients(your_room_name);

for(var i=0;i<socketsOfTheRoom.length;i++){
   sock = socketsOfTheRoom[i]
   if(sock===sessionid_of_new_connection){
      return true
   }
}

return false

OTHER TIPS

With the help of @Jujuleder I figured out how to solve my issue.

Server:

var socketio = require('socket.io'),
    cookieParser = require('cookie-parser')('YOUR-SERECT-KEY'),
    session = require('express-session'),
    RedisStore = require('connect-redis')(session),
    redis = require("redis"),
    client = redis.createClient(6379, "127.0.0.1"),
    store = new RedisStore;

module.exports.listen = function(app){
   var io = socketio.listen(app);
   var pubRoom = new PublicRoom(io);
   pubRoom.listen();
   return io
};

function PublicRoom(io){
   this._baseUrl = '/room/public/';
   this.publicRoom = io.of(this._baseUrl);
}

PublicRoom.prototype.listen = function(){
   this.publicRoom.authorization(function(handshakeData, callback){

   function cookieParserWrapper (handshakeData, next) {
       cookieParser(handshakeData,{}, next);
   }

   cookieParserWrapper(handshakeData,function(){});

   var sid = handshakeData.signedCookies.sid;
   //get the UID from redis
   store.get(sid,function(err,data){
      if(err){
            console.log(err);
       }else{
            handshakeData.uid = data.uid;//set UID into handshake
            callback(null, true);
        }
   });
});

this.publicRoom.on('connection', function(socket){
    socket.on('authReq',function(room,user){
        socket.myID = user;
        var uid = socket.handshake.uid; // We can get the UID here.
        var onlineUsers = self.publicRoom.clients(room);//get users in this room
        if(onlineUsers.length === 0){
            socket.to(room).emit('authRes',true);// Tell the client you can Join
            socket.auth = true;
        }else{
            for(var i= 0,l=onlineUsers.length;i<l;i++){
                if(onlineUsers[i].myID===uid){
                    socket.auth = false;
                    socket.to(room).emit('authRes',false);
                    // Tell the client you can't Join
                }else{
                    socket.auth = true;
                    socket.to(room).emit('authRes',true);// Tell the client you can Join
                }
            }
        }
    });
 });
}

client:

socket.on('connect', function() {
    socket.emit('authReq',roomID,userID);
});

//SERVER.JS

socket.on('authReq',function(room,user, callback){
         if (io.nsps['/'].adapter.rooms[room])
         {
            var onlineUsers = io.sockets.adapter.rooms[room].sockets;
            var totalUsers = io.sockets.adapter.rooms[room];
            if(totalUsers.length === 0){
                callback(true);
            }
            else
            {
                var userinroom = [];
                for (var id in onlineUsers) {
                  if (io.of('/').adapter.nsp.connected[id].username==user)
                      userinroom.push(user);                      
                }               
                if (userinroom.length==0) callback(true);
                else callback(false);
            }
         }
         else
            callback(true);
    });

// CLIENT.JS

socket.emit('authReq',roomname,username, function(callback) {
                    if(callback) 
                        if (username) socket.emit('adduser', username, rooname);
                });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top