Skip to content

Instantly share code, notes, and snippets.

@rebolyte
Created April 13, 2021 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebolyte/eb925a7cd45a333352e0a7d713b6e68c to your computer and use it in GitHub Desktop.
Save rebolyte/eb925a7cd45a333352e0a7d713b6e68c to your computer and use it in GitHub Desktop.
const { Publisher, Subscriber } = require('zeromq');
const PORT = 5000;
const args = process.argv.slice(2);
const TOPIC = args[0] || 'doc1';
let n = 0;
const publisher = async () => {
const pub = new Publisher();
await pub.bind(`tcp://127.0.0.1:${PORT}`);
console.log(`Publisher bound to port ${PORT}`);
while (n < 10) {
console.log('sending');
const msg = {
instanceId: process.pid,
content: 'hello'
};
await pub.send([TOPIC, JSON.stringify(msg)]);
await new Promise(resolve => setTimeout(resolve, 500));
n++;
}
};
const subscriber = async () => {
const sub = new Subscriber();
sub.connect(`tcp://127.0.0.1:${PORT}`);
sub.subscribe(TOPIC);
console.log(`Subscriber connected to port ${PORT}`);
for await (const [topic, msgBuf] of sub) {
const msg = JSON.parse(msgBuf.toString());
if (msg.instanceId !== process.pid) {
console.log(`received update for ${topic}:`, msg.content);
}
}
};
const main = async () => {
try {
subscriber();
publisher();
} catch (err) {
console.log(err);
process.exit(1);
}
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment