javascript - how to disconnect socket on session expire -
i have small express application contains socket program. when ever user success login creates session , socket connection perfectly.
but problem when express session expire or session delete cookie manager, socket still in active connection. receiving messages. how disconnect if session not available after success login.
here code was:
this html file gets 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 socket , 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 authentication code// req.session.login='logedin'; req.session.save(); res.sendfile('./template.html'); }); app.get('/', auth,function(req, res){ //index file contins 2 text boxes user name , 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.
maybe can check if req.session exists before emitting message ?
app.get('/alert',function(req,res){ if(req.session) io.sockets.in('sairam').emit('message',{msg:'hai'}); else //disconnect client server side res.end(); });
for disconnecting socket server side check answer;
Comments
Post a Comment