没有数据库写入的流星信号

Meteor signaling without db write

我一直在寻找一个好的方法,但还没有找到任何看起来不靠谱的东西。我想在不通过数据库和订阅的情况下向客户端发出信号。例如,在游戏中我想发送消息给客户端显示"Player 1 almost scores!"。我不关心长运行中的这些信息,所以我不想把它推到DB。我想我可以设置另一个 socket.io,但如果有在 meteor 中进行的好方法,我宁愿不必管理第二个连接。谢谢! (顺便说一句,查看了 Meteor Streams,但它似乎已失效)

使用数据库完成这样的任务完全没问题。 也许创建一个 "Streams" 的集合,您可以在其中存储预期的接收者和消息,客户端订阅他的流并观察它的任何变化。 然后,您可以在客户端完成处理后从数据库中删除流。 这比重新发明轮子和从头开始编写一切要容易得多。

你知道 Meteor 通过 Publish and Subscribe 机制提供从服务器到客户端的实时通信,通常用于发送你的 MongoDB 数据和以后的修改。

您想要一个类似的推送系统,但不必将一些数据记录到您的 MongoDB。

完全有可能重新使用 Meteor Pub/Sub 系统但没有数据库部分:而使用 Meteor.publish 你通常 return 一个集合游标,因此数据来自你的数据库,您还可以使用它的低级 API 发送任意实时信息:

Alternatively, a publish function can directly control its published record set by calling the functions added (to add a new document to the published record set), changed (to change or clear some fields on a document already in the published record set), and removed (to remove documents from the published record set). […]

只是不要 return 任何东西,使用上面提到的方法并且不要忘记在发布函数结束时调用 this.ready()

另请参阅有关 Custom publications

的指南
// SERVER
const customCollectionName = 'collection-name';
let sender; // <== we will keep a reference to the publisher

Meteor.publish('custom-publication', function() {
  sender = this;

  this.ready();

  this.onStop(() => {
    // Called when a Client stops its Subscription
  });
});

// Later on…
// ==> Send a "new document" as a new signal message
sender.added(customCollectionName, 'someId', {
  // "new document"
  field: 'values2'
});

// CLIENT
const signalsCollectionName = 'collection-name'; // Must match what is used in Server
const Signals = new Mongo.Collection(signalsCollectionName);
Meteor.subscribe('custom-publication'); // As usual, must match what is used in Server

// Then use the Collection low-level API
// to listen to changes and act accordingly
// https://docs.meteor.com/api/collections.html#Mongo-Cursor-observe
const allSignalsCursor = Signals.find();
allSignalsCursor.observe({
  added: (newDocument) => {
    // Do your stuff with the received document.
  }
});

那么如何以及何时使用 sender.added() 完全取决于您。

注意:请记住,它会将数据单独发送到客户端(每个客户端都有自己的服务器会话)

如果您想同时向多个客户端广播 消息,那么最简单的方法是使用您的MongoDB 作为服务器会话之间的粘合剂。如果您不关心实际的持久性,那么只需一遍又一遍地重复使用相同的文档并在您的客户端集合游标观察器中听取更改而不是添加。