【问题标题】:Why do I get the new data but node.js does not send the data?为什么我得到了新数据,但 node.js 没有发送数据?
【发布时间】:2014-11-25 11:04:31
【问题描述】:

我使用此代码在 mongo 数据库中获取新插入并将其发送到 html 文件:

mongo.MongoClient.connect (uristring, function (err, db) { 
        db.collection ("speed", function (err,collection) {
        collection.isCapped(function (err, capped) { 
        if (!capped) {
        console.log (collection.collectionName + " is not a capped collection");
        }
        else
        {
          var cursorOptions = {
          tailable: true,
          awaitdata: true,
          numberOfRetries: -1
        };
        var stream = collection.find({},{value:1,_id:0},cursorOptions).sort({$natural: -1}).stream();

        stream.on('data', function(document) {
          io.sockets.on('connection', function(socket){
          socket.emit('message', {'message': document});
        });
        });
        }
        });
    });
});

在客户端:

var socket = io.connect('/');
  var myValue = [];
  socket.on('message',function(data){
    console.log(data);
    myValue.push(data.message.value);

我一开始读取数据时它工作正常,但是当我在服务器运行时插入新数据时,数据显示在服务器中但不发送到客户端。

【问题讨论】:

  • 那么,您是否在客户端打开了一个 websocket 连接,正在监听 message
  • 是的.. var socket = io.connect('/'); var myValue = []; socket.on('message',function(data){ console.log(data); myValue.push(data.message.value);

标签: javascript node.js mongodb socket.io


【解决方案1】:
 stream.on('data', function(document) {
            socket.emit('message', {'message': document});
          io.sockets.on('connection', function(socket){
          socket.emit('message', {'message': document});
        });
        });

在您的第一个 socket.emit() 中,您指的是哪个套接字? 删除你的第一个 socket.emit 将解决问题。

stream.on('data', function(document) {
          io.sockets.on('connection', function(socket){
          socket.emit('message', {'message': document});
        });
        });

或者改变你的代码如下也应该可以正常工作。

io.sockets.on('connection', function(socket){
              stream.on('data', function(document) {
                    socket.emit('message', {'message': document});
                    });
                });

【讨论】:

  • 你保证你的socket.io服务器和socket.io客户端连接成功了吗?如果是,那么上面应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-27
  • 2019-08-13
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多