freeCodeCamp/curriculum/challenges/chinese/06-information-security-and.../advanced-node-and-express/communicate-by-emitting.chi...

2.9 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
589fc831f9fc0f352b528e75 Communicate by Emitting 2 通过发射进行沟通

Description

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

Instructions

Tests

tests:
  - text: currentUsers已定义
    testString: 'getUserInput => $.get(getUserInput("url")+ "/_api/server.js").then(data => {assert.match(data, /currentUsers/gi, "You should have variable currentUsers defined");}, xhr => { throw new Error(xhr.statusText); })'
  - text: 服务器在每个新连接上发出当前用户计数
    testString: 'getUserInput => $.get(getUserInput("url")+ "/_api/server.js") .then(data => { assert.match(data, /io.emit.*("|")user count("|").*currentUsers/gi, "You should emit "user count" with data currentUsers"); }, xhr => { throw new Error(xhr.statusText); })'
  - text: 您的客户正在侦听“用户计数”事件
    testString: 'getUserInput => $.get(getUserInput("url")+ "/public/client.js") .then(data => { assert.match(data, /socket.on.*("|")user count("|")/gi, "Your client should be connection to server with the connection defined as socket"); }, xhr => { throw new Error(xhr.statusText); })'

Challenge Seed

Solution

// solution required