What would be the best way of doing an all-to-all communication, would it be best to do a pub-sub with everyone subscribing to everyone else, or is there a socket type better suited for this?
You can achieve this with XPUB/XSUB proxy; many clients talking to many other clients; overview in the guide here.
The proxy acts as the intermediary for connecting many-to-many clients; example from expresso.c. The proxy runs standalone:
void *subscriber = zsocket_new (ctx, ZMQ_XSUB);
zsocket_bind (subscriber, "tcp://*:6000");
void *publisher = zsocket_new (ctx, ZMQ_XPUB);
zsocket_bind (publisher, "tcp://*:6001");
zmq_proxy (subscriber, publisher, 0);
The client plays the role of publisher and subscriber at the same time. In the main thread, create a pub socket, connect that to the XSUB side of the proxy; use this for sending messages.
void *publisher = zsocket_new (ctx, ZMQ_PUB);
zsocket_connect (publisher, "tcp://localhost:6000");
Now, you'll want to create a child thread in the client that listens for messages from the proxy on XPUB:
void *subscriber = zsocket_new (ctx, ZMQ_SUB);
zsocket_connect (subscriber, "tcp://localhost:6001");
When the client publishes a messages, all clients listening on XSUB will get it, including the client that sent the message, so keep that in mind.
If you don't need bidirectional messaging, implement PubClient and SubClient, each one playing the intended role for either sending or receiving, but not both; the above client code would simply be split into two classes for that approach.
Again, there are other ways of doing this, but this is most straightforward. hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With