Javascript 如何防止超过2个tokbox客户端?
我有以下代码:Javascript 如何防止超过2个tokbox客户端?,javascript,angular,opentok,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 <
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);
}
});
}
openTokInit(){
this.session=OT.initSession(this.tokboxApiKey,this.sessionId);
const self=这个;
this.session.on('connectionCreated',函数(事件){
self.connectionCount++;
});
如果(此.connectionCount<2){
this.session.connect(this.token,err=>{
如果(错误){
拒绝(错误);
}否则{
决议(本次会议);
}
});
}
问题是,当if语句运行时,connectionCount始终为0,因为“connectionCreated”事件在几秒钟后触发。我不清楚如何在连接新会话之前适当地等待所有connectionCreated事件触发。这里是OpenTok团队的Adam 在连接之前,您不会收到“connectionCreated”事件。因此,如果您已连接,并且您是第三个(或更多)用户,则需要断开连接参与者。我会使用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);
session=OT.initSession(apiKey,sessionId);
让connectionsBeforeUs=0;
会话.on('connectionCreated',(事件)=>{
if(event.connection.connectionId!==session.connection.connectionId&&
event.connection.creationTime=2){
//我们应该走了,前面已经有两个或更多的人了
警报(“此房间已满”);
session.disconnect();
}
}
});
会话连接(令牌);
我不确定您的整个应用程序是如何工作的,但另一种选择可能是在服务器端执行此操作,并且只向用户分发两个令牌进行连接。因此,当用户尝试获取第三个令牌时,您会在此时阻止他们。而不是让他们连接到会话,然后断开连接。这种方法的优点是您可以更快地通知用户,更快地给用户反馈。此外,恶意用户不能只是黑客的javascript和连接无论如何。您还可以使用跟踪用户从您的服务器连接
另一种选择是,如果房间里已经有两个人,则使用该功能将他们踢出房间。因此,已经在房间里的人有责任将第三个参与者踢出房间,而不是第三个参与者注意到房间里已经有人并离开自己。这意味着此人无法在浏览器中破解JavaScript代码并加入其他人的房间
在不了解整个应用程序的情况下,很难知道什么是最适合您的选项
我希望这会有所帮助!您可以添加另一个变量来跟踪当前正在创建的会话数。它将在
openTokInit
的第一行递增@ArnaudDenoyelle openTokInit每个设备/浏览器调用一次,因此计数器将始终为1。也许您可以使用“connecting:boolean”成员变量,该变量在启动“连接”时设置为true,在解析或拒绝连接时设置为false。在openTokInit的顶部放置一个简单的if语句“if(this.connecting){return;}”另外,我会将这个OT.initSession移到ngOnInit生命周期钩子中。谢谢Adam,在你回复之前我做了类似的事情。我会在连接ID进入时保留一个数组,如果当前会话连接ID与数组中前2个不匹配,我会断开连接并给出错误。这也行得通。我认为这样可能更安全gh希望以这种方式看待连接时间,而不是依赖事件的顺序。它们可能会以正确的顺序出现,但不能保证总是如此。