# Node.js 进程通信
# 场景
- 不同主机上两个 Node.js 进程间通信
- 同一主机上两个 Node.js 进程间通信
# 不同电脑上
# 使用TCP 套接字
# 使用HTTP
# 同一主机
虽然网络 socket 也可用于同一台主机的进程间通讯(通过 loopback 地址 127.0.0.1),但是这种方式需要经过网络协议栈、需要打包拆包、计算校验和、维护序号和应答等,就是为网络通讯设计的,而同一台电脑上的两个进程可以有更高效的通信方式,即 IPC(Inter-Process Communication),在 unix 上具体的实现方式为 unix domain socket,这是服务器端和客户端之间通过本地打开的套接字文件进行通信的一种方法,与 TCP 通信不同,通信时指定本地文件,因此不进行域解析和外部通信,所以比 TCP 快,在同一台主机的传输速度是 TCP 的两倍
# 使用内置IPC通信
如果是跟自己创建的子进程通信,是非常方便的,child_process 模块中的 fork 方法自带通信机制,无需关注底层细节
# 使用自定义的管道
如果是两个独立的 Node.js 进程,如何建立通信通道呢?在 Windows 上可以使用命名管道(Named PIPE),在 unix 上可以使用 unix domain socket
,也是一个作为 server,另外一个作为 client,其中 server.js 代码如下:
//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