2

Stop creation of new connection in different tab in node express and socket

I am developing a chatting app which made to run on port 3000 using node, express and socket.

I just want to stop creation of socket connection between client and server if other tab of same browser hits same url.

Can some one please help me out in this. I know I have to use session and cookies but I m unable to manage session within io.sockets.on('connection');

Thanks in advance.

1 Answers1

0

based on this post . answer by pr0zac

Create an express Session Store , you can use redis or whatever .... we will use to session cookie later

//better to use redis store
MemoryStore = require('connect/middleware/session/memory'),
var session_store = new MemoryStore();

app.configure(function () {
  app.use(express.session({ store: session_store }));
});

on Connection Event Handler

var connect = require('connect');
io.on('connection', function(socket_client) {
  var cookie_string = socket_client.request.headers.cookie;
  var parsed_cookies = connect.utils.parseCookie(cookie_string);
  var connect_sid = parsed_cookies['connect.sid'];
  if (connect_sid) {
    session_store.get(connect_sid, function (error, session) {

      if(session.lastConnected - Date.now() < HALF_HOUR) {
         socket_client.close()
      } else {
         session.lastConnected = Date.now()
      }
  });

  socket_client.on('disconnect', function () {
      if (connect_sid) {
        session_store.get(connect_sid, function (error, session) {
          // reset lastconnected
          session.lastConnected = 0;
        }
     });
  });
 }

});

I'm using express session object , to determine if the connection's timestamp delta is less than half and hour ( this can be modified ). if it does happen i close to socket, else i update lastConnected to now.

socket_client.on('disconnect', function() { ....

on disconnect event i reset the session lastConnected flag on socket .

Community
  • 1
  • 1
doron aviguy
  • 2,554
  • 2
  • 22
  • 18