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
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.