How to implement a simple Pub-Sub ZeroMQ relationship between a Python publisher and a C ++ subscriber?

I'm new to ZMQ and trying to implement a simple Pub-Sub relationship between a Python publisher and a C ++ subscriber. After the official documentation, I came up with this code:

Python Publisher

import zmq
import datetime

context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://127.0.0.1:5555")

while True:
    now = datetime.datetime.now()
    nowInMicroseconds = str(now.microsecond)
    socket.send_string(nowInMicroseconds)
    print("sending time in microseconds")

C ++ Subscriber

#include <zmq.hpp>
#include <iostream>

int main ()
{
    zmq::context_t context (1);
    zmq::socket_t subscriber (context, ZMQ_SUB);
    subscriber.connect("tcp://127.0.0.1:5555");
    subscriber.setsockopt(ZMQ_SUBSCRIBE, "");

    while(true) {   
        std::cout << "Getting data" << std::endl;
        zmq::message_t update;
        subscriber.recv(&update);
        std::cout << "Data received" << std::endl;

    }
}

But when I run the codes, I don't get any data with Python. What am I doing wrong?

EDIT

Running Python Publisher with a Python subscriber as user3666197offered very well. Starting C ++ Publisher with C ++ Subscriber works like a charm.

+4
source share
1 answer

First, we highlight the problem:

Create another follower on , in python: .connect()

import zmq
import datetime

pass;      Pcontext = zmq.Context()
Psocket  = Pcontext.socket( zmq.SUB )

Psocket.connect( "tcp://127.0.0.1:5555" )

Psocket.setsockopt( zmq.LINGER,     0 )
Psocket.setsockopt( zmq.SUBSCRIBE, "" )
Psocket.setsockopt( zmq.CONFLATE,   1 )

while True:
    print( "{1:}:: Py has got this [[[{0:}]]]".format( Psocket.recv(),
                                                       str( datetime.datetime.now()
                                                            )
                                                       )
            )

, , . , ( u'' Py 3+).

+1

Source: https://habr.com/ru/post/1689724/


All Articles