ZeroMQ上的NodeJS对等通信

时间:2019-06-14 07:46:18

标签: node.js zeromq

有几个NodeJS应用程序,它们会在'Zeromq'上进行对话并相互提供指示。

ZeroMQ的示例更具推拉/推动功能,并且在点对点通信中没有发现太多。

但是,ZeroMQ确实支持对等通信,示例均在python中。因此,分享在NodeJS中对我有用的代码。

1 个答案:

答案 0 :(得分:0)

解决此问题的方法是使用“ pair”选项连接套接字。

//Peer Client code
const socket = require(`zeromq`).socket(`pair`);
const address = process.env.ZMQ_PUB_ADDRESS || `tcp://127.0.0.1:3000`;
console.log(`Connecting to ${address}`);
socket.connect(address);
socket.on(`message`, function (msg) {
console.log(`Message received: ${msg}`);
});

const sendMessage2 = function () {
    const message = `Ping 2`;
    console.log(`Sending 2 '${message}'`);
    socket.send(message);
};
setInterval(sendMessage2, 30000);

//Peer Server Code
const socket = require(`zeromq`).socket(`pair`);
const address = process.env.ZMQ_BIND_ADDRESS || `tcp://127.0.0.1:3000`;  
console.log(`Listening at ${address}`);
socket.bindSync(address);

const sendMessage = function () {
    const message = `Ping 1`;
    console.log(`Sending 1 '${message}'`);
    socket.send(message);
};
setInterval(sendMessage, 2000);

socket.on(`message`, function (msg) {
    console.log(`Message received 2: ${msg}`);
});