我有以下代码:
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事件触发。
亚当来自OpenTok团队。
在连接之后,您将无法获得“connectionCreated”事件。因此,如果您已连接并且您是第3(或更多)参与者,则需要断开连接。我会使用connection.creationTime来查看谁首先到达那里以避免两个人大约在同一时间连接并且他们两个都断开连接。像这样的东西应该做的伎俩:
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个令牌。所以当他们试图获得第三个令牌时,你就会阻止他们。而不是让他们连接到会话,然后断开自己。这种方法的优点是您可以更快地注意到并尽快给予用户反馈。此外,恶意用户不仅可以破解javascript并进行连接。您还可以使用session monitoring API跟踪从您的服务器连接的用户。
另一种选择是使用forceDisconnect()功能将人们踢出房间,如果那里已经有2个人。因此,已经在房间里的人员有责任将第三个参与者踢出,而不是第三个参与者注意到那里已经有人并离开了自己。这意味着恶意的人无法破解浏览器中的JavaScript代码并加入其他人的房间。
虽然很难知道什么是最适合您的选择,但不知道您的整个应用程序。
我希望这有帮助!