1

I have a small express application this also contains the socket program. When ever user success login it creates the session and socket connection perfectly.

But MY problem was when the express session expire or session delete by cookie manager, the socket still in the active connection. it receiving the messages. how to disconnect even if the session are not available after the success login.

Here my code was:

This is my html file which gets the alert message:

<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="socket.io.js"></script>

<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: './alert'
    });
});
</script>

<script>
  var socket = io.connect();
  socket.on('message',function(data){
  alert(data.msg);
  });
</script>

</head>
<body>
<button>alert</button>
</bodY>
</html>

This is my socket and express code:

var express=require('express');
var app=express();
var session = require('express-session');
var server=require('http').createServer(app);
app.use(session({secret: 'abcd',resave:'false', saveUninitialized:'false',name:'usess',cookie: { maxAge: 10000 }));
var io=require('socket.io').listen(server);

 io.sockets.on('connection', function (socket) {
        socket.join('alerts');
        socket.on('disconnect',function(data){
            socket.leave('alerts');
            console.log('leaved');
        });
    });

app.get('/login', function(req, res){
  //here my authentication code//
  req.session.login='logedin';
  req.session.save();
  res.sendfile('./template.html');
});

app.get('/', auth,function(req, res){
  //index file contins the two text boxes for user name and pass//
  res.sendfile('./index.html');
});

app.get('/alert',function(req,res){
  io.sockets.in('alerts').emit('message',{msg:'hai'});
  res.end();
});

server.listen(3000);

Thank You.

teja
  • 43
  • 1
  • 6

1 Answers1

0

Maybe you can check if the req.session exists before emitting the message ?

app.get('/alert',function(req,res){
  if(req.session)
      io.sockets.in('sairam').emit('message',{msg:'hai'});
  else
      //Disconnect the client from server side
  res.end();
});

For disconnecting the socket from server side check this answer;

https://stackoverflow.com/a/5560187/3928819

Community
  • 1
  • 1
cdagli
  • 1,578
  • 16
  • 23