Home Web Front-end JS Tutorial Detailed explanation of the principle of port reuse in Node.Js

Detailed explanation of the principle of port reuse in Node.Js

May 05, 2018 am 11:28 AM
javascript node.js principle

This article mainly introduces the detailed explanation of the principle of port reuse in Node.Js. It has certain reference value. Now I share it with you. Friends in need can refer to it.

This article introduces Node.Js A detailed explanation of the principle of port reuse is shared with everyone. The details are as follows:

Origin, see multi-process shared ports from official examples

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
 console.log(`Master ${process.pid} is running`);

 for (let i = 0; i < numCPUs; i++) {
  cluster.fork();
 }

 cluster.on(&#39;exit&#39;, (worker, code, signal) => {
  console.log(`worker ${worker.process.pid} died`);
 });
} else {
 http.createServer((req, res) => {
  res.writeHead(200);
  res.end(&#39;hello world\n&#39;);
 }).listen(8000);

 console.log(`Worker ${process.pid} started`);
}
Copy after login

Execution result:

$ node server.js
Master 3596 is running
Worker 4324 started
Worker 4520 started
Worker 6056 started
Worker 5644 started

Understand the http.js module:

We all only need to create an http service and must reference the http module. The http module will eventually call net.js to implement network services

// lib/net.js
&#39;use strict&#39;;

 ...
Server.prototype.listen = function(...args) {
  ...
 if (options instanceof TCP) {
   this._handle = options;
   this[async_id_symbol] = this._handle.getAsyncId();
   listenInCluster(this, null, -1, -1, backlogFromArgs); // 注意这个方法调用了cluster模式下的处理办法
   return this;
  }
  ...
};

function listenInCluster(server, address, port, addressType,backlog, fd, exclusive) {
// 如果是master 进程或者没有开启cluster模式直接启动listen
if (cluster.isMaster || exclusive) {
  //_listen2,细心的人一定会发现为什么是listen2而不直接使用listen
 // _listen2 包裹了listen方法,如果是Worker进程,会调用被hack后的listen方法,从而避免出错端口被占用的错误
  server._listen2(address, port, addressType, backlog, fd);
  return;
 }
 const serverQuery = {
  address: address,
  port: port,
  addressType: addressType,
  fd: fd,
  flags: 0
 };

// 是fork 出来的进程,获取master上的handel,并且监听,
// 现在是不是很好奇_getServer方法做了什么
 cluster._getServer(server, serverQuery, listenOnMasterHandle);
}
 ...
Copy after login

The answer can be found quickly through the cluster._getServer function

  1. Proxy server._listen2 this method Execution operations in the work process

  2. Send queryServer message to master and register an internal TCP server with master

// lib/internal/cluster/child.js
cluster._getServer = function(obj, options, cb) {
 // ...
 const message = util._extend({
  act: &#39;queryServer&#39;,  // 关键点:构建一个queryServer的消息
  index: indexes[indexesKey],
  data: null
 }, options);

 message.address = address;

// 发送queryServer消息给master进程,master 在收到这个消息后,会创建一个开始一个server,并且listen
 send(message, (reply, handle) => {
   rr(reply, indexesKey, cb);       // Round-robin.
 });

 obj.once(&#39;listening&#39;, () => {
  cluster.worker.state = &#39;listening&#39;;
  const address = obj.address();
  message.act = &#39;listening&#39;;
  message.port = address && address.port || options.port;
  send(message);
 });
};
 //...
 // Round-robin. Master distributes handles across workers.
function rr(message, indexesKey, cb) {
  if (message.errno) return cb(message.errno, null);
  var key = message.key;
  // 这里hack 了listen方法
  // 子进程调用的listen方法,就是这个,直接返回0,所以不会报端口被占用的错误
  function listen(backlog) {
    return 0;
  }
  // ...
  const handle = { close, listen, ref: noop, unref: noop };
  handles[key] = handle;
  // 这个cb 函数是net.js 中的listenOnMasterHandle 方法
  cb(0, handle);
}
// lib/net.js
/*
function listenOnMasterHandle(err, handle) {
  err = checkBindError(err, port, handle);
  server._handle = handle;
  // _listen2 函数中,调用的handle.listen方法,也就是上面被hack的listen
  server._listen2(address, port, addressType, backlog, fd);
 }
*/
Copy after login

The master process starts the service after receiving the queryServer message

  1. If the address has not been monitored, start the service through RoundRobinHandle monitoring

  2. If the address has been monitored, directly bind the handle to the service that has been monitored to consume the request

// lib/internal/cluster/master.js
function queryServer(worker, message) {

  const args = [
    message.address,
    message.port,
    message.addressType,
    message.fd,
    message.index
  ];

  const key = args.join(&#39;:&#39;);
  var handle = handles[key];

  // 如果地址没被监听过,通过RoundRobinHandle监听开启服务
  if (handle === undefined) {
    var constructor = RoundRobinHandle;
    if (schedulingPolicy !== SCHED_RR ||
      message.addressType === &#39;udp4&#39; ||
      message.addressType === &#39;udp6&#39;) {
      constructor = SharedHandle;
    }

    handles[key] = handle = new constructor(key,
      address,
      message.port,
      message.addressType,
      message.fd,
      message.flags);
  }

  // 如果地址已经被监听,直接绑定handel到已经监听到服务上,去消费请求
  // Set custom server data
  handle.add(worker, (errno, reply, handle) => {
    reply = util._extend({
      errno: errno,
      key: key,
      ack: message.seq,
      data: handles[key].data
    }, reply);

    if (errno)
      delete handles[key]; // Gives other workers a chance to retry.

    send(worker, reply, handle);
  });
}
Copy after login

See this In the first step, it is already obvious that we know the implementation principle of multi-port sharing

  1. In fact, the port is only listened once by the internal TCP server in the master process

  2. Because the net.js module will determine whether the current process is the master or the Worker process

  3. If it is the Worker process, call cluster._getServer to hack the native listen method

  4. So the listen method called in child is an empty method that returns 0, so the port occupation error will not be reported

Now the problem is coming, since How does the Worker process obtain the connect received by the master process listening service?

  1. Listen to the connection event of the TCP server started by the master process

  2. Select a worker through polling

  3. Send newconn internal message to it, the message body contains the client handle

  4. With the handle, everyone knows how to deal with it haha

// lib/internal/cluster/round_robin_handle.js

function RoundRobinHandle(key, address, port, addressType, fd) {

  this.server = net.createServer(assert.fail);

  if (fd >= 0)
    this.server.listen({ fd });
  else if (port >= 0)
    this.server.listen(port, address);
  else
    this.server.listen(address); // UNIX socket path.

  this.server.once(&#39;listening&#39;, () => {
    this.handle = this.server._handle;
    // 监听onconnection方法
    this.handle.onconnection = (err, handle) => this.distribute(err, handle);
    this.server._handle = null;
    this.server = null;
  });
}

RoundRobinHandle.prototype.add = function (worker, send) {
  // ...
};

RoundRobinHandle.prototype.remove = function (worker) {
  // ...
};

RoundRobinHandle.prototype.distribute = function (err, handle) {
  // 负载均衡地挑选出一个worker
  this.handles.push(handle);
  const worker = this.free.shift();
  if (worker) this.handoff(worker);
};

RoundRobinHandle.prototype.handoff = function (worker) {
  const handle = this.handles.shift();
  const message = { act: &#39;newconn&#39;, key: this.key };
  // 向work进程其发送newconn内部消息和客户端的句柄handle
  sendHelper(worker.process, message, handle, (reply) => {
  // ...
    this.handoff(worker);
  });
};
Copy after login

Let’s take a look at what operations the Worker process performed after receiving the newconn message

// lib/child.js
function onmessage(message, handle) {
  if (message.act === &#39;newconn&#39;)
   onconnection(message, handle);
  else if (message.act === &#39;disconnect&#39;)
   _disconnect.call(worker, true);
 }

// Round-robin connection.
// 接收连接,并且处理
function onconnection(message, handle) {
 const key = message.key;
 const server = handles[key];
 const accepted = server !== undefined;

 send({ ack: message.seq, accepted });

 if (accepted) server.onconnection(0, handle);
}
Copy after login

Summary

  1. net module will determine whether the process is a worker or a master. If it is a worker, it will hack the net.Server instance. listen method

  2. The listen method called by worker is hacked and returns 0 directly, but a connection event will be registered with the master

  3. After the master receives the client connection event, it will poll and send the client handle from the connection to the worker.

  4. The worker receives the client handle sent by the master, and then it can process the client. Requested

Related recommendations:

Node implements static resource server

The above is the detailed content of Detailed explanation of the principle of port reuse in Node.Js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Analysis of the function and principle of nohup Analysis of the function and principle of nohup Mar 25, 2024 pm 03:24 PM

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

In-depth discussion of the principles and practices of the Struts framework In-depth discussion of the principles and practices of the Struts framework Feb 18, 2024 pm 06:10 PM

Principle analysis and practical exploration of the Struts framework. As a commonly used MVC framework in JavaWeb development, the Struts framework has good design patterns and scalability and is widely used in enterprise-level application development. This article will analyze the principles of the Struts framework and explore it with actual code examples to help readers better understand and apply the framework. 1. Analysis of the principles of the Struts framework 1. MVC architecture The Struts framework is based on MVC (Model-View-Con

In-depth understanding of the batch Insert implementation principle in MyBatis In-depth understanding of the batch Insert implementation principle in MyBatis Feb 21, 2024 pm 04:42 PM

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values

An in-depth discussion of the functions and principles of Linux RPM tools An in-depth discussion of the functions and principles of Linux RPM tools Feb 23, 2024 pm 03:00 PM

The RPM (RedHatPackageManager) tool in Linux systems is a powerful tool for installing, upgrading, uninstalling and managing system software packages. It is a commonly used software package management tool in RedHatLinux systems and is also used by many other Linux distributions. The role of the RPM tool is very important. It allows system administrators and users to easily manage software packages on the system. Through RPM, users can easily install new software packages and upgrade existing software

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Detailed explanation of the principle of MyBatis paging plug-in Detailed explanation of the principle of MyBatis paging plug-in Feb 22, 2024 pm 03:42 PM

MyBatis is an excellent persistence layer framework. It supports database operations based on XML and annotations. It is simple and easy to use. It also provides a rich plug-in mechanism. Among them, the paging plug-in is one of the more frequently used plug-ins. This article will delve into the principles of the MyBatis paging plug-in and illustrate it with specific code examples. 1. Paging plug-in principle MyBatis itself does not provide native paging function, but you can use plug-ins to implement paging queries. The principle of paging plug-in is mainly to intercept MyBatis

An in-depth analysis of the functions and working principles of the Linux chage command An in-depth analysis of the functions and working principles of the Linux chage command Feb 24, 2024 pm 03:48 PM

The chage command in the Linux system is a command used to modify the password expiration date of a user account. It can also be used to modify the longest and shortest usable date of the account. This command plays a very important role in managing user account security. It can effectively control the usage period of user passwords and enhance system security. How to use the chage command: The basic syntax of the chage command is: chage [option] user name. For example, to modify the password expiration date of user "testuser", you can use the following command

The basic principles and methods of implementing inheritance methods in Golang The basic principles and methods of implementing inheritance methods in Golang Jan 20, 2024 am 09:11 AM

The basic principles and implementation methods of Golang inheritance methods In Golang, inheritance is one of the important features of object-oriented programming. Through inheritance, we can use the properties and methods of the parent class to achieve code reuse and extensibility. This article will introduce the basic principles and implementation methods of Golang inheritance methods, and provide specific code examples. The basic principle of inheritance methods In Golang, inheritance is implemented by embedding structures. When a structure is embedded in another structure, the embedded structure has embedded

See all articles