如何断开会话上的套接字过期 [英] how to disconnect socket on session expire

查看:38
本文介绍了如何断开会话上的套接字过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小型快递应用程序,它还包含套接字程序.一旦用户成功登录,它就会完美地创建会话和套接字连接.

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.

但是我的问题是当快速会话到期或cookie管理器删除会话时,套接字仍处于活动连接中.它收到消息.成功登录后即使会话不可用也如何断开连接.

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.

我的代码是:

这是我的html文件,它收到警报消息:

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);

谢谢.

推荐答案

也许您可以在发出消息之前检查req.session是否存在?

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

这篇关于如何断开会话上的套接字过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆