Divide the session between sockets. (Exit all active tabs)

I am creating a simple chat learning application using the node.js express framework. And I have one problem. If the user has several active tabs, he leaves one tab. I want to close the connection to other tabs and redirect to the login page. But I ran into a problem. Even if the user is logged out, other socket sessions do not change (I use the passport.socketio package, so I have the current user in socket.handshake.user). What am I doing wrong? Thanks in advance.

+4
source share
2 answers

If you have n different tabs, there are actually the number n of different sockets. One way to achieve what you want is to make all sockets from a specific user attached to the same room .

io.on('connection', function (socket) {
    socket.join(socket.handshake.user.id);
    // rest of your code
}

And in the exit code, output the "logout" event to this particular room.

io.sockets.in(socket.handshake.user.id).emit('logout')

Now on the client side you can write an event listener in "logout", which redirects you to the right place.

+4
source

In your application, you will need to view all open sockets, find the corresponding username and end them manually.

0
source

All Articles