I am trying to see if a ZMQ_REP server is ready to communicate with clients using the following code by polling the server every 1 second but it never returns true although the server is up and running for listening to clients.
#include <iostream>
#include <zmq.hpp>
#include <chrono>
const std::string SERVER_ENDPOINT = "tcp://localhost:5555";
bool checkServer(const std::string& serverEndpoint) {
zmq::context_t context(1);
zmq::socket_t socket(context, zmq::SocketType::REQ);
socket.connect(serverEndpoint);
zmq::pollitem_t items [] = {{ socket, 0, ZMQ_POLLIN, 0 }};
zmq::poll(items, 1, 1000); // 1 second timeout
if (items[0].revents & ZMQ_POLLIN) {
return true; // If server is available
}
return false;
}
int main() {
bool serverAvailable = false;
while (!serverAvailable) {
std::cout << "Waiting for server..." << std::endl;
serverAvailable = checkServer(SERVER_ENDPOINT);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Server is available." << std::endl;
return 0;
}
I would appreciate it if someone could shed light on this issue.
In your example you create a
ZMQ_REQsocket, connect it, then wait for a incoming message. This will not work as yourZMQ_REPserver (code not seen) cannot send without first receiving a message from aZMQ_REQsocket.As an example you can have multiple
ZMQ_REQclients connected to oneZMQ_REPserver. Internally each client has its own routing ID and the server uses this to direct the replies to the correct clients.