简体   繁体   中英

Node.js Socket.io sets up multiple connections

Im creating a simple socket.io chat that uses passport.js for authentication. But everytime a user logout and login the old socket connection reconnects. This causes a problem because now there are two active connections to one page. So what I want to do is end the current connection when the user navigates to "/logout".

var socketNotLoaded = true;
var socket;

app.get('/', function(req, res) {
    if (req.isAuthenticated()) {
        if(socketNotLoaded) { //is true when new connection is required
            require("./socket")(io,req.user) //runs the socket.io script
            socketNotLoaded = false;
        }
        res.render('index', pug.get(req.user));
    } else {
        res.render('notloggedin', pug.get());
    }
})

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

Im using

  • socket.io: 2.0.3
  • passport: 0.4.0
  • passport-local: 1.0.0
  • express: 4.15.4
  • express-session: 1.15.5
  • cookie-parser: 1.4.3
  • body-parser: 1.17.2

On the client-side when the user wants to logout, you could perform a socket.emit('exit'); , then on the server-side have a listener like so:

socket.on('exit', function(){
    socket.disconnect();
});

And that will disconnect the client from Socket.io. You could also create an object on the server-side that maps a username to a Socket.io socket ID, and perform a check to see if that user already exists. If it does, then you can disconnect that socket ID on the server-side. Ideally, the client should send a disconnect to the server when the user logs out. Something like this:

 $('#logout').click( function() {
            socket.disconnect();
            window.location = "/logout";
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM