Issue checking if a ZeroMQ server is ready to talk to clients

34 views Asked by At

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.

1

There are 1 answers

0
jamesdillonharvey On

In your example you create a ZMQ_REQ socket, connect it, then wait for a incoming message. This will not work as your ZMQ_REP server (code not seen) cannot send without first receiving a message from a ZMQ_REQ socket.

As an example you can have multiple ZMQ_REQ clients connected to one ZMQ_REP server. Internally each client has its own routing ID and the server uses this to direct the replies to the correct clients.