1

I have a phonegap app in which i connect to my node.js socket like so:

var socket  = io.connect('http://54.213.92.113:8080');

It works fine but when I go to a different page, the socket gets disconnected.

I could just write the same code in the javascript on the next page but that's messier than I think it needs to be - as it would open up a new connection when it could have just stayed connected in the first place.

Is there any way to stay connected to the socket even if I switch pages?

pj409
  • 337
  • 2
  • 9
  • 21

2 Answers2

4

suppose you have a multi-page application then ,here you can do a trick that when your socket gets connected first time when the page loads then you can assign the session id to that particular connection like this.and then bind that connection to that session.

 io.on('connection', function(socket) {

 socket.on('start-session', function(data) {
            console.log("============start-session event================")
            console.log(data)
            if (data.sessionId == null) {
                var session_id = uuidv4(); //generating the sessions_id and then binding that socket to that sessions 
                socket.room = session_id;
                socket.join(socket.room, function(res) {
                    console.log("joined successfully ")
                    socket.emit("set-session-acknowledgement", { sessionId: session_id })


            } else {
                socket.room = data.sessionId;  //this time using the same session 
                socket.join(socket.room, function(res) {
                    console.log("joined successfully ")
                    socket.emit("set-session-acknowledgement", { sessionId: data.sessionId })
                })
            }
        });

Now you had binded the socket connection to a session now you are sending an acknowledgement too at the client side also .There what you can do is that store the session id to the web browsers session storage like this

At client side code

 socket.on("set-session-acknowledgement", function(data) {
  sessionStorage.setItem('sessionId', data.sessionId);

 })

This will store the session id in the browsers session storage.Now when the page is navigated from page1 to page2 and so on. then send that session id to the server so that you will be connected to the same session logically like this

  var session_id;
            // Get saved data from sessionStorage
            let data = sessionStorage.getItem('sessionId');
            console.log(data)
            if (data == null) {
                session_id = null//when we connect first time 
                socket.emit('start-session', {  sessionId: session_id })
            } else {
                session_id = data//when we connect n times 
                socket.emit('start-session', {  sessionId: session_id })
            }

So basically the logic behind is that we can use same session for multiple socket connections by doing this as every time the socket will be joined to that particular room only and emit the events which you can listen on server side and vice a versa.

shubham yadav
  • 172
  • 1
  • 5
  • 1
    This question was asked forever ago and your solution to the question is elegant and spot on. I'll be using a form of this solution in my implementation. My site is actually using a PHP backend so it already will have a session ID so I'll be binding that rather than generating it, but I have ideas on how to improve security by generating it for other applications I'm working on. Thanks. – Andrew Apr 24 '20 at 07:10
0

Only if you build it as a single page application where the actual page doesn't reload load when navigating. However it would probably be better to design your socket.io code and your server side to be resilient to frequent socket connect / disconnect. This is especially true for code written to run on a cell phone.

Timothy Strimple
  • 22,920
  • 6
  • 69
  • 76
  • Thanks for the advice! Quick question...would my app connect to the socket as the same client (with the same id) when it switches pages? If so, I could put a timer on the server that will look for a disconnected client for a few seconds. – pj409 Aug 14 '13 at 21:10
  • 1
    You'll likely get a different socket id each page. You shouldn't equate a socket id with a user, you should use something more persistent like a cookie. Then when a new socket connection comes in, you can check the cookie to see which user the connection belongs to. See this answer for how to handle it using express sessions: http://stackoverflow.com/questions/12166187/manage-multiple-tabs-but-same-user-in-socket-io – Timothy Strimple Aug 14 '13 at 21:15