Haribe
Haribe

Reputation: 11

ZeroMQ python to c++ Pub / Sub

I have a below python code, which is successfully working in python - python PUB/SUB ZeroMQ ( pyzmq ) scenario.

Can I subscribe this python server through c++ ?

I added a c++ client code too, which did not work.

Python:

def send_array_and_str(socket, img, string, flags=0):
    global count
    print(count , "  sended")
    ## numpy array gönderirken shape bilgilerini de msg olarak eklemek lazım
    md = dict(dtype=str(img.dtype), shape=img.shape)
    socket.send_string(str(count), flags | zmq.SNDMORE)
    socket.send_string(string, flags | zmq.SNDMORE)

    socket.send_json(md, flags | zmq.SNDMORE)
    socket.send(img, flags)
    count += 1
    # print(count)
    return


context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:5667")

C++

zmq::socket_t subscriber (context, ZMQ_SUB);
subscriber.connect("tcp://localhost:5556");

zmq::message_t update;
subscriber.recv(&update);

total_temp += temperature;

Upvotes: 1

Views: 1815

Answers (2)

user3666197
user3666197

Reputation: 1

Can I subscribe this python server through c++ ?

Oh sure you can.

The above presented client code did not work, well, actually it did work as defined by the API, as you did subscribe the SUB-side to nothing.

So it indeed received nothing, fully compliant and in line with the documented ZeroMQ API.

It would be also useful to direct the .connect()-method to the very same port# ~ 5667, if you wish the SUB to be ever delivered anything meaningful from there serving PUB, wouldn't it?

Upvotes: 0

SamR
SamR

Reputation: 336

Your producer (publisher) and consumer (subscriber) may be in any language that has a ZeroMQ binding/library.

Your producer must...

  1. Bind a PUB socket to an endpoint.
  2. Send messages to the PUB socket.

Your consumer must...

  1. ... connect a SUB socket to the same endpoint (host:port) that the producer binds to (in this case, "tcp://localhost:5556").
  2. ... subscribe to a topic using zmq_setsockopt. This lets the producer know to send messages to the consumer. (Your subscriber does not do this.)

A subscription topic is the leading characters of a message, or of the first message part in a multipart message. An empty string may be passed as the topic to receive all messages (I just think of it as the minimum prefix string). See [http://api.zeromq.org/2-1:zmq-setsockopt].

zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0);

Upvotes: 1

Related Questions