meteor - 获取发布方法的所有订阅者会话句柄

时间:2015-07-02 09:30:16

标签: meteor

我想将NON-MONGO-DB数据从服务器发布者广播到客户端集合。目前,我保存所有已注册的订阅者句柄以使用它们发布数据

client.js:

col = new Meteor.Collection("data")

Meteor.subscribe("stream")

在服务器端,它看起来像

server.js

all_handles = [];

Meteor.publish("stream", function() {
  // safe reference to this sessions
  var self = this;
  // save reference to this subscriber
  all_handles.push(self);
  // signal ready
  self.ready();
  // on stop subscription remove this handle from list
  self.onStop(function() {
    all_handles = _.without(all_handles, self); 
  }
}

然后我可以在我的应用程序中的某个地方使用all_handles将数据发送到这些客户端,例如:

function broadcast(msg) {
  all_handles.forEach(function(handle) {
    handle.added("data", Random.id(), msg);
  }
}

这已经在使用并正在运行。

问:我正在寻找的是:我可以从当前已存在的流星(内部)对象(例如_sessions或其他内容)中获取所有句柄吗?

如果我不能自己组织订阅者处理,那就太棒了。

请不要回答其他广播套餐的链接,例如streamy或其他。我希望继续使用标准集合,但代码尽可能少。

感谢您的帮助和反馈 汤姆

2 个答案:

答案 0 :(得分:1)

也许这可能适合您:https://stackoverflow.com/a/30814101/2005564

你可以通过var connections = Meteor.server.stream_server.open_sockets;获得连接,但正如looshi所说,这可能会破坏未来的流星更新,因为它不是公共API的一部分......

答案 1 :(得分:1)

正如@laberning所知,我现在使用的是“未记录的”流星连接。

您可以向所有订阅者发布以下发布方法:

// publish updated values to all subscribers
function publish_to_all_subscribers(subscription_name, id, data) {
  _.each(Meteor.server.stream_server.open_sockets, function(connection) {
    _.each(connection._meteorSession._namedSubs, function(sub) {
      if (sub._name == subscription_name) {
        sub.insert(subscription_name, id, data);
      }
    })
  });
}

// create stream publisher
Meteor.publish('stream', function(){
  // set ready
  this.ready();
});

...
// use publishing somewhere in your app
publish_to_all_subscribers('stream', Random.id(), {msg: "Hello to all"});
...

已更新:查看示例MeteorPad for Publish and Subscribe and Broadcast messages