简体   繁体   English

addListener 在 node.js 中做了什么?

[英]What does addListener do in node.js?

I am trying to understand the purpose of addListener in node.js .我试图了解node.js中 addListener 的目的。 Can someone explain please?有人可以解释一下吗? A simple example would be:一个简单的例子是:

var tcp = require('tcp');
var server = tcp.createServer(function (socket) {
  socket.setEncoding("utf8");
  socket.addListener("connect", function () {
    socket.write("hello\r\n");
  });
  socket.addListener("data", function (data) {
    socket.write(data);
  });
  socket.addListener("end", function () {
    socket.write("goodbye\r\n");
    socket.end();
  });
});
server.listen(7000, "localhost");

Due to the fact that Node.js works event-driven and executes an event-loop, registering listeners allow you to define callbacks that will be executed every time the event is fired.由于 Node.js 以事件驱动并执行事件循环这一事实,注册侦听器允许您定义每次触发事件时将执行的回调。 Thus, it is also a form of async.因此,它也是异步的一种形式。 code structuring.代码结构。

It's comparable to GUI listener, that fire on user interaction.它类似于 GUI 侦听器,它激发用户交互。 Like a mouse click, that triggers an execution of code in your GUI app, your listeners in your example will be run as soon as the event happens, ie a new client connects to the socket.就像鼠标点击一样,会触发 GUI 应用程序中代码的执行,您示例中的侦听器将在事件发生后立即运行,即新客户端连接到套接字。

it registers a listener for an "event".它为“事件”注册了一个监听器。 Events are identified by strings, such as "connect" and "data" .事件由字符串标识,例如"connect""data" the second argument is a function, a so called "callback", also refered to as "event handler".第二个参数是一个函数,即所谓的“回调”,也称为“事件处理程序”。 Whenever a specific event occurs within the object the listeners have been registered to, all handlers are invoked.每当侦听器注册到的对象中发生特定事件时,就会调用所有处理程序。

node.js uses this, because it employs an asynchronous execution model, that can best be handled with an event-driven approach. node.js 使用它,因为它采用异步执行模型,最好用事件驱动的方法处理。

greetz问候语
back2dos后退2dos

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM