如何防止2个以上的Tokbox客户端?

时间:2019-03-09 20:25:34

标签: javascript angular opentok

我有以下代码:

openTokInit() {
    this.session = OT.initSession(this.tokboxApiKey, this.sessionId);
    const self = this;
    this.session.on('connectionCreated', function(event) {
        self.connectionCount++;
    });

    if (this.connectionCount < 2) {
        this.session.connect(this.token, err => {
            if (err) {
                reject(err);
            } else {
                resolve(this.session);
            }
        });
    }

问题是当if语句运行时,connectionCount始终为0,因为几秒钟后会触发'connectionCreated'事件。我不清楚如何在连接新会话之前适当等待所有connectionCreated事件触发。

1 个答案:

答案 0 :(得分:1)

OpenTok团队的亚当。

直到连接后,您才能获得“ connectionCreated”事件。因此,如果您已连接并且您是第3个(或更多)参与者,则需要断开连接。我将使用connection.creationTime来查看谁先到达那里,以避免2个人大约同时连接,并且他们俩都断开了连接。这样的事情应该可以解决问题:

session = OT.initSession(apiKey, sessionId);
let connectionsBeforeUs = 0;
session.on('connectionCreated', (event) => {
  if (event.connection.connectionId !== session.connection.connectionId &&
     event.connection.creationTime < session.connection.creationTime) {
    // There is a new connection and they got here before us
    connectionsBeforeUs += 1;
    if (connectionsBeforeUs >= 2) {
      // We should leave there are 2 or more people already here before us
      alert('disconnecting this room is already full');
      session.disconnect();
    }
  }
});
session.connect(token);

Here is a jsbin that demonstrates it working

我不确定您的整个应用程序如何工作,但是另一种选择可能是在服务器端执行此操作,并且只分发2个令牌供人们连接。因此,当他们尝试获取第3个令牌时,您会在此时将其屏蔽。而不是让他们连接到会话,然后断开自己的连接。这种方法的优点是您可以更快地注意到并更快地向用户提供反馈。同样,恶意用户也不能只是破解JavaScript并进行连接。您还可以使用session monitoring API来跟踪从服务器连接的用户。

另一个选择是,如果房间中已经有2个人,则使用forceDisconnect()功能将其他人踢出房间。因此,已经在房间里的人有责任踢出第三位参与者,而不是第三位参与者,因为他注意到那里已经有人离开了自己。这将意味着恶意软件无法破解其浏览器中的JavaScript代码并进入其他人的房间。

尽管不知道整个应用程序是什么,但很难知道什么是最适合您的选择。

我希望这会有所帮助!

相关问题