-1

What is the simplest way to use ZeroMQ so that one sender sends out messages and an arbitrary number of receivers can get all those messages?

I would like to send messages which are Python objects (dicts) so I would like to use recv_json and send_json for that.

As I understand PUB/SUB will always require topics and will send multipart messages, which seems unnecessary with my use case. But I cannot see any other protocol which would do the same without the overhead.

Another complication (perhaps) is that this should work for both Python2 and Python3 receivers.

When there is no topic, can I just ignore the issue of topics when sending and receiving alltogether and use send/receiv_json as with other protocols?

jpp1
  • 2,019
  • 3
  • 22
  • 43

1 Answers1

1

You don't need to use topics for PUB/SUB; you can't just subscribe to "all topics" and then send whatever messages you want. E.g., I can write a publisher like this:

import json
import time
import zmq


c = zmq.Context()
s = c.socket(zmq.PUB)
s.bind("tcp://127.0.0.1:4321")

while True:
    s.send(json.dumps({"color": "red", "size": "large", "count": 10}).encode())
    time.sleep(0.5)

And a client like this:

import json
import zmq


c = zmq.Context()
s = c.socket(zmq.SUB)
s.connect('tcp://127.0.0.1:4321')
s.subscribe('')

while True:
    m = json.loads(s.recv())
    print(m)

It all works, and you'll note that I am neither making use of topics nor am I using multipart messages.

larsks
  • 277,717
  • 41
  • 399
  • 399