I am building a new version of my app with Node.js. Below you will find my winner countdown, where the output of console.log(counter)
, needs to be broadcasted with Socket.io to all clients.
var counter = 10;
var WinnerCountdown = setInterval(function(){
console.log(counter);
counter--
if (counter === 0) {
console.log("Congratulations You WON!!");
clearInterval(WinnerCountdown);
}
}, 1000);
My Socket.IO code is as follows:
setInterval(() => {
wss.clients.forEach((client) => {
client.send(new Date().toTimeString());
});
}, 1000);
What should I replace the new Date().toTimeString()
, so that it will show the message of console.log instead?
I am building a new version of my app with Node.js. Below you will find my winner countdown, where the output of console.log(counter)
, needs to be broadcasted with Socket.io to all clients.
var counter = 10;
var WinnerCountdown = setInterval(function(){
console.log(counter);
counter--
if (counter === 0) {
console.log("Congratulations You WON!!");
clearInterval(WinnerCountdown);
}
}, 1000);
My Socket.IO code is as follows:
setInterval(() => {
wss.clients.forEach((client) => {
client.send(new Date().toTimeString());
});
}, 1000);
What should I replace the new Date().toTimeString()
, so that it will show the message of console.log instead?
-
I think you want to move the state (in this case
counter
) to the server-side code (the second snippet). Then the client-side can have zero logic other than to listen for an event from the server andconsole.log(result)
. – styfle Commented Feb 22, 2017 at 17:57
1 Answer
Reset to default 4To broad cast to all clients you can use io.sockets.emit('counter', counter);
. Here is an example of a script you could use to achieve what (I think) you are trying to do:
server.js
io.on('connection', function(socket){
var counter = 10;
var WinnerCountdown = setInterval(function(){
io.sockets.emit('counter', counter);
counter--
if (counter === 0) {
io.sockets.emit('counter', "Congratulations You WON!!");
clearInterval(WinnerCountdown);
}
}, 1000);
});
client.js
var socket = io();
socket.on('counter', function(count){
$('#messages').append($('<li>').text(count));
});
Hope this helps, please ment if you have any follow up questions!