Can not send to specific client: Socket IO sends it to every client?

Viewed 141

Yes, I have gone through the documentation, which is very well written: Socket IO Cheatsheet

Here is the problem: I want to notify the user of a logout when his session from the Express App is being destroyed. Now this is what is happening: When I log out from the session, all other clients (including those who have or have not even logged in) get a message saying they're logged out. Yes, my express app is working fine - they are not getting logged off, but I believe SOCKET IO is sending them the message regardless. I ran the debugger and it turns out that both the clients are distinguishable, too.

Here is my code:

server.js:

var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.set('socketio', io);
io.on('connection', function (socket) {
  app.set('current_socket', socket);
  console.log('No of clients:', io.engine.clientsCount); 
});

userController.js:

exports.userLogout = function(req, res, next) {
    const sessionID = req.session.id;
    const io = req.app.get('socketio');
    const this_socket = req.app.get('current_socket');

    req.session.destroy(function (err){
        if(err) {
            console.error("userLogout failed with error:", err);
            return next(err);
        }
        else {
            console.log("this_socket:", this_socket);
            console.log("io:", io);
            this_socket.emit('userAction', { action: 'logout' });
            //other logic to remove old sessions from DB Session Store
            //and finally:
            res.status(200)
                .json({
                status: 'success',
                api_data: {'loggedIn':false},
                message: 'Logout successful.'
                });
        }
    }
}

I even tried this instead:

io.emit('userAction', { action: 'logout' });

but turns out it still emits to all the clients. I am pretty sure there is a mismatch somewhere, just can't figure out where.

2 Answers

You need create room for each session id if you want to send emits to spesific user

io.on('connection', function (socket) {
  app.set('current_socket', socket);
  var sessionId = socker.request.session.id
  //join room
  socket.join(sessionId);
});

userController.js:

exports.userLogout = function(req, res, next) {
    const sessionID = req.session.id;
    const io = req.app.get('socketio');
    const this_socket = req.app.get('current_socket');

    req.session.destroy(function (err){
        if(err) {
            console.error("userLogout failed with error:", err);
            return next(err);
        }
        else {
            console.log("this_socket:", this_socket);
            console.log("io:", io);
            this_socket.sockets.in(sessionID).emit('userAction', { action: 'logout' });
            //other logic to remove old sessions from DB Session Store
            //and finally:
            res.status(200)
                .json({
                status: 'success',
                api_data: {'loggedIn':false},
                message: 'Logout successful.'
                });
        }
    }
}

You have to define unique socket object for each user. We have many ways to do that.

In simple way, we use user id (unique) as a key to store socket object (Map way: key(userId) - vaule(socketObj)).

Follow the rabbit:

When a user loggedin, client side emits a event (login) to server side, the event include the user id.

Client Side:

// login success
socket.emit('userLoggedIn', {userId: THE_USER_ID})

Server Side:

io.on('connection', function (socket) {
  // app.set('current_socket', socket);
  console.log('No of clients:', io.engine.clientsCount);
  socket.on('userLoggedIn', function(data) => {
    app.set(data.userId, socket); // save socket object
  })
});

userController.js:

exports.userLogout = function(req, res, next) {
    const sessionID = req.session.id;
    const userId = MAGIC_GET_USER_ID_FROM_SESSION_ID(sessionID) // who want to logout
    const io = req.app.get('socketio');
    const this_socket = req.app.get(userId); // get "user socket"

    req.session.destroy(function (err){
        if(err) {
            console.error("userLogout failed with error:", err);
            return next(err);
        }
        else {
            console.log("this_socket:", this_socket);
            console.log("io:", io);
            this_socket.emit('userAction', { action: 'logout' });
            //other logic to remove old sessions from DB Session Store
            //and finally:
            res.status(200)
                .json({
                status: 'success',
                api_data: {'loggedIn':false},
                message: 'Logout successful.'
                });
        }
    }
}
Related