πter
πter

Reputation: 2217

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

I am new to ZMQ, and trying to implement a simple Pub-Sub communication between Python publisher and C++ subscriber. Following the official documentation I come up with these 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 won't receive any data from Python. What I am doing wrong ?

EDIT

Running Python Publisher with Python Subscriber as user3666197 suggested works just fine. Running C++ Publisher with C++ Subscriber works like charm.

Upvotes: 4

Views: 3314

Answers (1)

user3666197
user3666197

Reputation: 1

First, let's isolate the problem:

Create also another subscriber to .connect(), in python:

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()
                                                            )
                                                       )
            )

If this works as expected, the problem is not on the sender side. If this fails, may check a proper subscription string-handling issues on different platforms ( expecting u'' on Py 3+ ).

Upvotes: 1

Related Questions