提醒一下,这个项目是基于Glitch的以下入门项目构建的,或者是从GitHub克隆的。 Emit是您将使用的最常见的沟通方式。当您从服务器向'io'发送内容时,会将事件的名称和数据发送到所有连接的套接字。这个概念的一个很好的例子就是每次新用户连接时都会发出连接用户的当前数量!
首先添加一个变量,以便在您当前正在侦听连接之前跟踪用户。 var currentUsers = 0;
现在当有人连接时,你应该在发出计数之前递增计数,这样你就可以在连接监听器中添加增量器。 ++currentUsers;
最后,在递增计数后,您应该发出事件(仍在连接侦听器中)。该事件应命名为“用户计数”,数据应该只是'currentUsers'。 io.emit('user count', currentUsers);
现在,您可以为客户实施一种方式来监听此事件!与在服务器上侦听连接类似,您将使用on关键字。 socket.on('user count',function(data){
的console.log(数据);
});
现在尝试加载您的应用并进行身份验证,您应该在客户端控制台中看到“1”代表当前用户数!尝试加载更多客户端并进行身份验证以查看数量是否上升。当您认为自己已经做对时,请提交您的页面。
## Instructions