Rooms/Channels 和 Meteor.js 中的用户 ID

Rooms/Channels and userId in Meteor.js

我正在使用 meteor.js 构建多人回合制游戏。该应用程序将处理多个游戏,因此我想将我的用户分成不同的房间。 我在使用 socket.io 频道之前已经完成了,但我很难理解应该如何在 Meteor 中完成它。

我想要实现的流程是:

  1. 用户访问http://localhost:3000/join/userId

  2. 我使用 "sessionId" 作为参数对外部 API 进行服务器端调用,获取用户的 userId、他分配的 roomId 和该房间允许的 userId 数组

  3. 我想为用户创建一个带有 roomId 的房间或将他加入现有房间。我知道我应该创建一个 'Rooms' 集合,但我不知道如何将用户绑定到我的房间并仅向给定房间中的用户发布消息。

我想避免使用 'accounts' 包,因为我这边不需要授权 - 它将由上面提到的步骤 #2 处理 - 但如果最简单和最干净的方法这样做涉及到添加这个包,我可以改变主意。

您的 Rooms collection 可能看起来像:

{
    _id: "<auto-generated>",
    roomId: "roomId",
    users: [ "user1", "user2", "user3", ... ],
    messages: [
        { message: "", userId: "" },
        { message: "", userId: "" },
        { message: "", userId: "" },
        ...
    ]
}

server-sideAPI调用returns

userIdroomId 以及其他信息。

所以你可以做一个

Rooms.update({ roomId: roomId }, { $push: { users: userId } }, { upsert: true });

这会将用户推送到现有房间或创建一个新房间并添加用户。

您的发布函数可能如下所示:

Meteor.publish("room", function(roomId) {
    // Since you are not using accounts package, you will have to get the userId using the sessionId that you've specified or some other way.
    // Let us assume your function getUserId does just that.

    userId: getUserId( sessionId );
    return Rooms.find({ roomId: roomId, users: userId });

    // Only the room's users will get the data now.

});

希望对您有所帮助。