Wednesday 26 April 2017

Pass socket data from one user session to another non-asynchronously

I'm using node.js and sockets and have need to get data from one socket in a room, then when a new socket joins a room share that data to the new session.

More specifically, I'm attempting to start a timer on the client side on the first socket in the room, then pass the current timer position to the next socket that joins the room.

I'm using a basic timer like this on the client side:

setInterval(timer, 1000);    
  });
var seconds = 0;
function timer(seconds){
  socket.emit('clientTimer', seconds);
  seconds++;
  return seconds;
}

On the server side, I'm listening for the timer, then I want to emit that timer information to the next socket that joins the room.

socket.on('clientTimer', function(seconds){
   socket.emit('newClientTimer', seconds);
});

Since I'm using the same html file for both sockets, I have this on the client side:

socket.on('newClientTimer', function(seconds){
  console.log(seconds);
});

The problem here is it only emits the timer to the original client with the current time, and the new client starts over at 0. So now I have two timers instead of one.

Is it possible to grab only the current timer position and pass it from the server to the new room connection non-asynchronously? Or if that's the wrong way to phrase my question, please suggest a better way and I'll update my title.



via Dshiz

No comments:

Post a Comment