How to update the client HTML page according to the nodejs server outputs?

Problem

I developed an app using namespaces of nodejs where a client (client1) sends the data to the server, and the server sends the same data to another client (client2). Everything is working fine, except that the data is rendered in client2 only if i refresh the page.. How to update the data dynamically?

the codes are as following: server::

var io = require('socket.io').listen(8007);
    var chat = io
      .of('/chat')
      .on('connection', function (socket) {
        socket.on('message', function(message){
        console.log("Received message:: " + message + " - from client " + socket.id);
            var news = io
            .of('/news')
            .on('connection', function (socket1) {
            socket1.send("received::" + message + " - from client " + socket.id);
            });
    });
    });

and the client1 is::

<script>
var count=0;
function connect() {
  var chat = io.connect('http://localhost:8007/chat');
    chat.send('chat message:::' + count);
    count++;
  }
</script>

receiving client being::

<script>
  var news = io.connect('http://localhost:8007/news');
    news.on('message', function(data){
    document.getElementById('message').innerHTML = "\n Server says: " + data;
    });  
</script>
Problem courtesy of: Nachiketha

Solution

I think your problem is on the server. You aren't setting up your "news" listener until after you receive a connection to "chat". Change your server code to something like the following:

var io = require('socket.io').listen(8007);
var newsSocket;
var news = io
    .of('/news')
    .on('connection', function (socket1) {
        newsSocket = socket1;
    });
var chat = io
    .of('/chat')
    .on('connection', function (socket) {
        socket.on('message', function(message){
        console.log("Received message:: " + message + " - from client " + socket.id);
        for(var i=0; i<newsSockets.length; i++) {
            newsSocket.send("received::" + message + " - from client " + socket.id);
        }
    });

Note: This will only send the news message to the last client that connected. You should have a collection(array) of news connections. You should also remove them when they disconnect.

Solution courtesy of: DanBaker

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.