2

I have a working server that's using sockets. My server-side code looks like this:

io.sockets.on('connection', function(socket) {
  socket.emit('status', { counter: count });
});

In this example, I'm simply incrementing a counter by 1 every minute. When the counter updates, I'd like to send the current count to all clients. My index.html file looks like this:

<script>
var socket = io.connect('http://localhost');
socket.on('status', function (data) {
  console.log(data);
});
</script>

When I start up my server, I can see the first data send to the client {'counter': 0}, however when the value of the counter increments, I don't see the new value being updated on the client. Why isn't new data being sent to my clients?

turtle
  • 7,533
  • 18
  • 68
  • 97

2 Answers2

2

You emit the information only upon connection. For instance, if you just want to broadcast the information every minute - just change your code to:

io.sockets.on('connection', function(socket) {
  setInterval(function() {
    socket.emit('status', { counter: count });
  }, 60 * 1000);
});

This will create an interval upon connection, and then emit the message every minute.

If you want something more advanced, such as listening to the change in count you need to subscribe to changes from it using a more advanced mechanism.

Update

Another way to achieve this is to emit on counter change (using the same function that updates it).

Yet another way is to use the experimental observe feature on a javascript object.

Community
  • 1
  • 1
sheba
  • 800
  • 6
  • 14
0

This question was already answered.

See: Update all clients using Socket.io?

The basic info is: you need to emit the message form the global socket io not the individual socket.

The socket.emit() only emits to one socket. Where as io.socket.emit() will emit the message to all sockets (broadcast message).

Community
  • 1
  • 1
Chris Spiegl
  • 345
  • 3
  • 8