how to disconnect socket on session expire

邮差的信 提交于 2020-01-25 17:41:09

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/30641476/how-to-disconnect-socket-on-session-expire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!