1

I created a user login with nodejs and mongodb. I have a router. I stripped some of the code out below, but the main routes I am concerned with in this question are the /profile and /logout routes.

Basically I want to pass the req or res data to the socket when the route is made. Since the routes are on the server I am not sure how to emit the data. I mean typically you emit from client to server and the other way around, not server to server.

So maybe I am being blind or am not knowledgeable enough, but my question is how can I pass that data to my socket.

module.exports.initialize = function(app, passport) {

    app.get('/profile', isLoggedIn, function(req, res) {
        res.render('profile', { user : req.user });
        //socket.emit('user loggedIn', { user : req.user })
    });

    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });


    // route middleware to make sure a user is logged in
    function isLoggedIn(req, res, next) {
        if (req.isAuthenticated())
            return next();
        res.redirect('/');
    }

};

Side Note: My socket code sits in my server.js so example.

var users = {};

io.sockets.on('connection', function (socket) {

    // Listen to a new user then emit the user to all clients
    socket.on('user loggedIn', function (data) {

        socket.userName = data;
        users[socket.userName] = socket;
        io.sockets.emit('user name', Object.keys(users));
        console.log(users);

    });

});

Basically I want to just store all the logged in users inside an object and emit to the client all the logged in users and allow them to have a live chat.

It appears all I need to do is pass that data to my socket, so I am sure passing that data is simple, but I DONT KNOW HOW!

Thanks!

Michael Joseph Aubry
  • 12,282
  • 16
  • 70
  • 135
  • 1
    Just as an aside, I'm currently doing a similar set up, but when the user logs in, we save that session (which contains the user details), and the socket connects to the same session store. So in the socket `connect`, we also have access to the current user's session. Took advice from this [Stack answer](http://stackoverflow.com/a/11585839/1253609). – incutonez Mar 24 '14 at 19:42
  • Hey cool you're doing something similar, ill take a look hope it helps. – Michael Joseph Aubry Mar 24 '14 at 19:46

1 Answers1

0

Clint side code but username should be unique

socket.emit('myname',{username:'uniqueid});

server side code

var onlineuser=[];
socket.on('myname',function(data){
                      socket.username=data.username;
                   onlineuser.push(data.username);
                   io.sockets.emit('onlineuser',onlineuser);
              });

  socket.on('disconnect',function()
          {
              var i=onlineuser.indexOf(socket.username);
                 onlineuser.splice(i,1);
              io.sockets.emit('onlineuser',onlineuser);
          });
Murugan Pandian
  • 768
  • 1
  • 5
  • 17