Reputation: 23
I am unable to receive messages sent via ZeroMQ by a C++ publisher with a Python subscriber. Messages sent via Python publisher can be received by a Python subscriber but those sent through a C++ publisher can't.
Here's some more details and simplified code.
Python Subscriber
import zmq
import time
if __name__ == '__main__':
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.bind("tcp://127.0.0.1:98765")
socket.setsockopt_string(zmq.SUBSCRIBE, "")
while True:
print(socket.recv())
time.sleep(1)
C++ Publisher (not working)
#include <string>
#include <zmq.hpp>
#include <unistd.h>
using std::string;
int main() {
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_PUB);
socket.connect("tcp://127.0.0.1:98765");
string pub_msg = "greetings from C++";
zmq::message_t message_to_send(pub_msg.size());
memcpy(message_to_send.data(), pub_msg.c_str(), pub_msg.size());
socket.send(message_to_send, zmq::send_flags::dontwait);
usleep(10*1000000);
}
Python Publisher (working)
import zmq
import time
if __name__ == '__main__':
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.connect("tcp://127.0.0.1:98765")
while True:
socket.send("greetings from Python")
time.sleep(1)
I want to have the Python subscriber working with C++ publisher. I have tried binding the C++ publisher and connecting Python subscriber but that also doesn't work.
Some direction here would be very helpful.
Thanks Noman.
Upvotes: 0
Views: 862
Reputation: 1042
Regarding the C++ ZMQ_PUB version, its possible the message is being sent before the connect() establishes a connection as its async.
PUB will throw the message away if the connection is not established, PUSH on the other hand will queue.
Try adding a sleep between connect and send
Upvotes: 0
Reputation: 23
So, it turns out changing
Python
socket = context.socket(zmq.PULL) # from context.socket(zmq.SUB)
C++
zmq::socket_t socket(context, ZMQ_PUSH); // from socket(context, ZMQ_PUB)
helped fix my problem.
I don't have an explanation for it, but for my use-case, this should do.
Upvotes: 0