REQ-REP with ZeroMQ 3.1: client

Given a ØMQ 3.1 server (REP, the guy who replies), as written in the previous post, it is quite easy to write a client (REQ, the guy who sends a request).

The code is symmetrical. If the server waits on a receive for a client, and then send back to it an acknowledging message, the client sends a message, and than wait for the server reply. To add a bit of fun to the code, the client sends ten "real" messages, and then a "fake" (empty) one, that in the convention set in this application means a request to the server to shutdown:
void* context = zmq_init(1);
void* socket = zmq_socket(context, ZMQ_REQ);
zmq_connect(socket, "tcp://localhost:50013"); // 1

char* buffer = "Hello";
int size = strlen(buffer);
for(int i = 0; i < 10; ++i)
    std::cout << "Sending " << buffer << " [" << i << "]" << std::endl;
    zmq_send(socket, buffer, size, 0); // 2

    if(!receive(socket)) // 3

char* terminator = "";
zmq_send(socket, terminator, 0, 0); // 4

1. We are connecting in client mode, so have to provide the IP address of the machine where the server is. Here we have both part of the pattern in the same machine, so localhost is used. As for the server, protocol is "tcp" and the port number is matching.
2. Remember that in ZeroMQ 3.1 zmq_send() and zmq_recv() have an extra parameter, the size of the message to be sent.
3. The receive() function is shown in the server post. It executes zmq_recv() and return false if the message is empty or there is an error in receiving.
4. An empty message is sent to the server, before shutting down the client.

No comments:

Post a Comment