Inter-Process Communication (IPC) in Node.js, when using manager and clusters, refers to the mechanism that allows separate processes, such as the manager and its clusters, to exchange data and messages seamlessly, enabling efficient coordination and collaboration within a multi-process application.
Configuring
index.js
// Receive message from clusters.
manager.on('message', (message) => {
console.log(`Manager received a message ${message.data}.`);
// Reply to it.
message.reply('hello');
});
// Send message to a cluster.
const clusterId = 0;
const cluster = manager.clusters.get(clusterId);
// Send normal message.
cluster.send('test'); // -> void
// Send a request.
cluster.request('test2'); // -> "again" (client replies below)
// Send message to all clusters.
manager.broadcast('everyone!');
cluster.js
// Receive message from manager.
client.cluster.on('message', (message) => {
console.log(`Client received a message ${message.data}.`);
// Reply to it.
message.reply('again');
});
โ
// Send normal message to manager.
client.cluster.send('test'); // -> void
// Send a request.
client.cluster.request('test2'); // -> "hello" (manager replies above)
โ
// Send message to all clusters excluding itself.
client.cluster.broadcast('everyone!');
// Or add "true" to send to itself on listener.
client.cluster.broadcast('everyone and me!', true);