0

The issue that I'm having is http request happen independently or at different time as a web socket connection. The idea is that when a user connects I can store a session id and a web socket within the same pair in var allConnectionsMatches = [];and use this information later in a post request to find out which socket is calling the request so I can emit to that particular socket. The code below shows my attempt. What I wrote does work to an extent but It has a few issues such as when you refresh it sometimes doesnt emit messages anymore, or when you exit out the browser and connect again there is no message emitted by socket io. Any ideas?

var allConnectionsMatches = [];

var sessionID;

app.get('/', function(req, res, next) {

  sessionID = req.session.id;

  res.render('index.ejs')

});

function findDuplicates(data, sessionID, socket) {

    var isPositive = data.lastIndexOf(sessionID);

    if (isPositive === true) {

      var socketLocation = allConnectionsMatches.indexOf(sessionID);

      socketLocation + 1;

      allConnectionsMatches.splice(socketLocation, 1, socket)

    } else if(isPositive === -1) {

      data.push(sessionID, socket);
    } else {

    }

}


io.sockets.on('connection', function (socket) {
  findDuplicates(allConnectionsMatches, sessionID, socket)
});
  • `socket.handshake.headers.cookie` contains the cookies from when the socket.io connection was first connected. You can parse those cookies and should be able to find your session ID in the cookies. You should not be putting `sessionID` into a module level variable. That will get trounced by different users accessing your server so what you have now is a concurrency bug waiting to get hit. You should be using a real session manager to maintain a session for each connecting browser. – jfriend00 Aug 15 '16 at 06:43
  • Yeah, I'm using [express-session](https://www.npmjs.com/package/express-session) right now, could you possibly link me a session manager that I could use? – John Anderson Aug 15 '16 at 06:54
  • express-session will work just fine. You can probably find a socket.io-specific 3rd party module that will give you access to the express-session from your socket.io connect handler. Or, you can just parse the cookies, get the express-session cookie and access the express-session using that cookie value. – jfriend00 Aug 15 '16 at 06:55
  • For example, you may want to use [express-socket.io-session](https://www.npmjs.com/package/express-socket.io-session). – jfriend00 Aug 15 '16 at 12:35
  • And, [How to share sessions with socket.io and express](http://stackoverflow.com/questions/25532692/how-to-share-sessions-with-socket-io-1-x-and-express-4-x) – jfriend00 Aug 15 '16 at 12:39

0 Answers0