Created
April 13, 2021 20:43
-
-
Save rebolyte/eb925a7cd45a333352e0a7d713b6e68c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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