Node.js不更新客户端

时间:2013-06-14 15:26:44

标签: node.js socket.io

我有一个场景,我让Node通过net.socket连接从一个服务器提取数据,然后使用sockets.io输出到客户端浏览器。来自服务器的数据每分钟左右都会更新。如果我将该数据输出到控制台,它可以正常工作,显示更新。但是,我似乎无法通过socket.io将数据推送到浏览器。我很擅长PHP但是对javascript完全新手。我确实理解,因为数据是从服务器更新的,它应该触发一个“事件”,导致socket.io推出新数据。我很感激任何帮助。

 //set all variables and modules includes here
 // [...]

  server = http.createServer (function(req, res) {
     res.writeHead(200, {'Content-Type:' 'text/html'});
     res.end(index);
  }).listen(8080, localhost);

  //connection to stats server
  var socket = new net.Socket();
    socket.connect (6000, "xxx.xxx.xxx.xxx", function () {
    console.log("connected");
  });
    socket.on('data', function(data) {
      var buf = new Buffer(data, 'base64');
      var calls = buf.toString();
      console.log(calls); // if I include this, data outputs to console perfectly

   //set up socket.io connection to client
   var clientupdate = function clientupdate() {
      io.sockets.on('connection', function(socket) {
         socket.emit('calls', {data: calls});
      });
     }
   });

2 个答案:

答案 0 :(得分:0)

您没有调用clientupdate函数。你宣布它,但你不打电话。 您所需要的只是:

clientupdate();

答案 1 :(得分:0)

代码有几个问题:

  1. 永远不会调用clientUpdate函数,因此服务器根本不响应新客户端。
  2. 即使您确实调用了该函数,现在实现它的方式,服务器也只会发送连接后收到的第一组数据,但不会发送任何连续的结果。要解决此问题,您可以在io对象上发出消息,而不是将消息发送给所有连接的客户端。
  3. 结合这将看起来像这样(未经测试,但它应该工作):

     //set all variables and modules includes here
     // [...]
    
      server = http.createServer (function(req, res) {
         res.writeHead(200, {'Content-Type:' 'text/html'});
         res.end(index);
      }).listen(8080, localhost);
    
      //connection to stats server
      var socket = new net.Socket();
        socket.connect (6000, "xxx.xxx.xxx.xxx", function () {
        console.log("connected");
      });
    
      socket.on('data', function(data) {
        var buf = new Buffer(data, 'base64');
        var calls = buf.toString();
        console.log(calls); 
    
        //any data we have we emit to all the clients
        io.emit('calls', { data : calls });
      }); 
    

    请注意,由于从不使用各个连接,因此省略了整个io.on('connection')部分。只有当您需要与个人客户进行互动时才需要它。

相关问题