I am new to ZMQ and already did the tutorials about the publish subscribe pattern. But for my application they don't quite apply. I have two types of applications. Application one can create connections to multiple "Applications two"s over network and send them data.
I tried implementing this with the Publish/Subscribe pattern, but instead of the subscriber connecting to the publisher the publisher connects to the subscribers.
Publisher:
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_PUB);
socket.connect("tcp://localhost:5555");
std::string text = "Hello World";
zmq::message_t message(text.size());
memcpy(message.data(), text.c_str(), text.size());
socket.send(message);
Subscriber:
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_SUB);
socket.bind("tcp://*:5555");
const char* filter = "Hello ";
socket.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));
zmq::message_t request;
socket.recv(&request);
std::string message = std::string(static_cast<char*>(request.data()), request.size());
std::cout << "Message received!" << std::endl;
std::cout << message << std::endl;
The publisher finnishes without error, but the subscriber is stuck in the recv(). And yes I am starting them in the right order (subscriber first)
I found the solution myself: The problem is, that the publisher send the message, before the subscriber was ready to receive. A simple
zmq_sleep(1)
before the
socket.send(message);
did the job.