Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to connect 5 publishers with 5 subscribers over TCP using ZeroMQ's XPUB/XSUB proxy
// How to connect 5 publishers with 5 subscribers
// over TCP using ZeroMQ's XPUB/XSUB proxy.
// sub (connect)
// <-8701->
// (bind) xpub <---> xsub (bind)
// <-8700->
// (connect) pub
var zmq = require('zmq');
// xsub/xpub
var xsub = zmq.socket('xsub');
xsub.bindSync('tcp://*:8700');
var xpub = zmq.socket('xpub');
xpub.setsockopt(zmq.ZMQ_XPUB_VERBOSE, 1);
xpub.bindSync('tcp://*:8701');
// Message pump
xsub.on('message', function (topic, data) {
xpub.send([ topic, data ]);
});
// Subscription pump
xpub.on('message', function (data) {
xsub.send(data);
});
// Subscribers
for (var i = 1; i <= 5; i++) {
(function (i) {
var subscriber = zmq.socket('sub');
subscriber.subscribe('Topic 1');
subscriber.on('message', function (topic, data) {
console.log('Subscriber', i, 'received', data.toString(), 'on topic', topic.toString());
});
subscriber.connect('tcp://localhost:8701');
})(i);
}
// Publishers
for (var i = 1; i <= 5; i++) {
(function (i) {
var publisher = zmq.socket('pub');
publisher.connect("tcp://localhost:8700");
var msg = 1;
setInterval(function () {
publisher.send(['Topic 1', 'message ' + msg++ + ' from publisher ' + i]);
}, 500 * i);
})(i);
}
@abacaj
Copy link

abacaj commented Dec 3, 2015

awesome thanks for the example 👍

Copy link

ghost commented Nov 11, 2016

👍

@mnshh17
Copy link

mnshh17 commented Mar 16, 2020

Hello guys can you please explain how xpub xsub are connected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment