Reputation: 3341
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 js 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.
Upvotes: 0
Views: 80
Reputation: 6698
Sorry to say it, but it looks like there's a long way to go before the code does what you're describing.
The server doesn't relay the timer to other clients.
socket.on('clientTimer', function(seconds){
socket.emit('newClientTimer', seconds);
});
You'll need to send it to other sockets. I can't post a "fixed" code snippet either, because it's not clear how you're keeping track of the sockets connected to the other clients in the room.
This code sends the timer back to the same socket from which it received it.
Each new client starts at zero because it uses the same page, which initializes with
var seconds = 0;
Maybe you're trying to receive a timer value on the client with
socket.on('newClientTimer', function(seconds){
console.log(seconds);
});
but it's not working, because the argument named seconds
is its own variable, and it doesn't update the var seconds
variable in the outer scope. Because the argument's name shadows the variable outside, now you can't even assign from one to the other.
You probably want something like
socket.on('newClientTimer', function(newSeconds){
console.log(newSeconds);
seconds = newSeconds;
});
Upvotes: 1