


Explain how to communicate between two Node.js processes in different scenarios!
Node.js进程间如何进行通信?下面本篇文章给大家介绍一下分场景介绍两个 Node.js 进程间进行通信的方法,希望对大家有所帮助!
两个 Node.js 进程之间如何进行通信呢?这里要分两种场景:
不同电脑上的两个 Node.js 进程间通信
同一台电脑上两个 Node.js 进程间通信
【推荐学习:《nodejs 教程》】
对于第一种场景,通常使用 TCP 或 HTTP 进行通信,而对于第二种场景,又分为两种子场景:
Node.js 进程和自己创建的 Node.js 子进程通信
Node.js 进程和另外不相关的 Node.js 进程通信
前者可以使用内置的 IPC 通信通道,后者可以使用自定义管道,接下来进行详细介绍:
不同电脑上的两个 Node.js 进程间通信
要想进行通信,首先得搞清楚如何标识网络中的进程?网络层的 ip 地址可以唯一标识网络中的主机,而传输层的协议和端口可以唯一标识主机中的应用程序(进程),这样利用三元组(ip 地址,协议,端口)就可以标识网络的进程了。
使用 TCP 套接字
TCP 套接字(socket)是一种基于 TCP/IP 协议的通信方式,可以让通过网络连接的计算机上的进程进行通信。一个作为 server 另一个作为 client,server.js 代码如下:
const net = require('net') const server = net.createServer(socket => { console.log('socket connected') socket.on('close', () => console.log('socket disconnected')) socket.on('error', err => console.error(err.message)) socket.on('data', data => { console.log(`receive: ${data}`) socket.write(data) console.log(`send: ${data}`) }) }) server.listen(8888)
client.js 代码:
const net = require('net') const client = net.connect(8888, '192.168.10.105') client.on('connect', () => console.log('connected.')) client.on('data', data => console.log(`receive: ${data}`)) client.on('end', () => console.log('disconnected.')) client.on('error', err => console.error(err.message)) setInterval(() => { const msg = 'hello' console.log(`send: ${msg}`) client.write(msg) }, 3000)
运行效果:
$ node server.js client connected receive: hello send: hello $ node client.js connect to server send: hello receive: hello
使用 HTTP 协议
因为 HTTP 协议也是基于 TCP 的,所以从通信角度看,这种方式本质上并无区别,只是封装了上层协议。server.js 代码为:
const http = require('http') http.createServer((req, res) => res.end(req.url)).listen(8888)
client.js 代码:
const http = require('http') const options = { hostname: '192.168.10.105', port: 8888, path: '/hello', method: 'GET', } const req = http.request(options, res => { console.log(`statusCode: ${res.statusCode}`) res.on('data', d => process.stdout.write(d)) }) req.on('error', error => console.error(error)) req.end()
运行效果:
$ node server.js url /hello $ node client.js statusCode: 200 hello
同一台电脑上两个 Node.js 进程间通信
虽然网络 socket 也可用于同一台主机的进程间通讯(通过 loopback 地址 127.0.0.1),但是这种方式需要经过网络协议栈、需要打包拆包、计算校验和、维护序号和应答等,就是为网络通讯设计的,而同一台电脑上的两个进程可以有更高效的通信方式,即 IPC(Inter-Process Communication),在 unix 上具体的实现方式为 unix domain socket,这是服务器端和客户端之间通过本地打开的套接字文件进行通信的一种方法,与 TCP 通信不同,通信时指定本地文件,因此不进行域解析和外部通信,所以比 TCP 快,在同一台主机的传输速度是 TCP 的两倍。
使用内置 IPC 通道
如果是跟自己创建的子进程通信,是非常方便的,child_process 模块中的 fork 方法自带通信机制,无需关注底层细节,例如父进程 parent.js 代码:
const fork = require("child_process").fork const path = require("path") const child = fork(path.resolve("child.js"), [], { stdio: "inherit" }); child.on("message", (message) => { console.log("message from child:", message) child.send("hi") })
子进程 child.js 代码:
process.on("message", (message) => { console.log("message from parent:", message); }) if (process.send) { setInterval(() => process.send("hello"), 3000) }
运行效果如下:
$ node parent.js message from child: hello message from parent: hi message from child: hello message from parent: hi
使用自定义管道
如果是两个独立的 Node.js 进程,如何建立通信通道呢?在 Windows 上可以使用命名管道(Named PIPE),在 unix 上可以使用 unix domain socket,也是一个作为 server,另外一个作为 client,其中 server.js 代码如下:
const net = require('net') const fs = require('fs') const pipeFile = process.platform === 'win32' ? '\\\\.\\pipe\\mypip' : '/tmp/unix.sock' const server = net.createServer(connection => { console.log('socket connected.') connection.on('close', () => console.log('disconnected.')) connection.on('data', data => { console.log(`receive: ${data}`) connection.write(data) console.log(`send: ${data}`) }) connection.on('error', err => console.error(err.message)) }) try { fs.unlinkSync(pipeFile) } catch (error) {} server.listen(pipeFile)
client.js 代码如下:
const net = require('net') const pipeFile = process.platform === 'win32' ? '\\\\.\\pipe\\mypip' : '/tmp/unix.sock' const client = net.connect(pipeFile) client.on('connect', () => console.log('connected.')) client.on('data', data => console.log(`receive: ${data}`)) client.on('end', () => console.log('disconnected.')) client.on('error', err => console.error(err.message)) setInterval(() => { const msg = 'hello' console.log(`send: ${msg}`) client.write(msg) }, 3000)
运行效果:
$ node server.js socket connected. receive: hello send: hello $ node client.js connected. send: hello receive: hello
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Explain how to communicate between two Node.js processes in different scenarios!. For more information, please follow other related articles on the PHP Chinese website!

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
