Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to communicate between two Node.js processes

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to communicate between two Node.js processes". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to communicate between two Node.js processes.

How do two Node.js processes communicate? There are two scenarios here:

Communication between two Node.js processes on different computers

Communication between two Node.js processes on the same computer

[recommended: "nodejs tutorial"]

For the first scenario, TCP or HTTP is usually used for communication, while for the second scenario, there are two sub-scenarios:

The Node.js process communicates with the Node.js child process created by itself

Node.js processes communicate with other unrelated Node.js processes

The former can use the built-in IPC communication channel, while the latter can use custom pipes, which are described in more detail:

Communication between two Node.js processes on different computers

In order to communicate, you must first figure out how to identify the processes in the network. The ip address of the network layer can uniquely identify the host in the network, while the protocol and port of the transport layer can uniquely identify the application (process) in the host, so that the triple (ip address, protocol, port) can be used to identify the process of the network.

Use TCP sockets

TCP socket (socket) is a communication method based on the TCP/IP protocol that allows processes on computers connected through the network to communicate. One as server and the other as client,server.js code is as follows:

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 Code:

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)

Running effect:

$node server.jsclient connectedreceive: hellosend: hello$ node client.jsconnect to serversend: helloreceive: hello

Use the HTTP protocol

Because the HTTP protocol is also based on TCP, from a communication point of view, this approach is essentially no different, but encapsulates the upper layer protocol. The server.js code is:

Const http = require ('http') http.createServer ((req, res) = > res.end (req.url)) .salary (8888)

Client.js Code:

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 ())

Running effect:

$node server.jsurl / hello$ node client.jsstatusCode: 200hello communicates between two Node.js processes on the same computer

Although network socket can also be used for inter-process communication of the same host (via loopback address 127.0.0.1), this method needs to go through the network protocol stack, need to pack and unpack packets, calculate checksum, maintain sequence number and reply, etc., which is designed for network communication, and the two processes on the same computer can have a more efficient communication mode, namely IPC (Inter-Process Communication), which is implemented on unix by unix domain socket. This is a method of communication between the server and the client through a socket file that is opened locally. Unlike TCP communication, the local file is specified when communicating, so there is no domain resolution and external communication, so it is faster than TCP, and the transmission speed on the same host is twice that of TCP.

Use the built-in IPC channel

If you are communicating with a child process created by yourself, it is very convenient. The fork method in the child_process module has its own communication mechanism, so you do not need to pay attention to the underlying details, such as the parent process parent.js code:

Const fork = require ("child_process"). Forkconst 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 process child.js code:

Process.on ("message", (message) = > {console.log ("message from parent:", message);}) if (process.send) {setInterval () = > process.send ("hello"), 3000)}

The running effect is as follows:

$node parent.jsmessage from child: hellomessage from parent: himessage from child: hellomessage from parent: hi

Use Custom Pip

If it is two separate Node.js processes, how to establish a communication channel? Named pipes (Named PIPE) can be used on Windows, and unix domain socket can be used on unix, one as server and the other as client, where the server.js code is as follows:

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)

The client.js code is as follows:

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)

Running effect:

$node server.js socket connected.receive: hellosend: hello$ node client.jsconnected.send: helloreceive: hello Thank you for reading, the above is the content of "how to communicate between two Node.js processes". After the study of this article, I believe you have a deeper understanding of how to communicate between the two Node.js processes, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report