Search code examples
c++tcpzeromq

ZeroMQ C++ req-rep termination error


Here is ZeroMq C++ code for simple request - reply where both exchange messages alternatively. But error occures when messages are only sent continuously ....

Reply code :

include zmq.hpp
include string
include iostream
include unistd.h
include ctime

    int main () {
// Prepare our context and socket
  zmq::context_t context (1);
  zmq::socket_t socket (context, ZMQ_REP);
  socket.bind ("tcp://*:5557");
  zmq::message_t reply (5);

  memcpy ((void *) reply.data (), "World", 5);
  zmq::message_t request;

// Wait for next request from client
  socket.recv (&request);
///////////////// """observe_line_1"""
  std::cout << "Received Hello" << std::endl;
  while (true)
  {
 // Send reply back to client
    socket.send (reply);
  }
  return 0;
}

Request code :

include zmq.hpp
include string
include iostream
include ctime

int main ()
{
  zmq::context_t context (1);
  zmq::socket_t socket (context, ZMQ_REQ);

  socket.connect ("tcp://localhost:5557");
  zmq::message_t request (6);
  memcpy ((void *) request.data (), "Hello", 5);
  zmq::message_t reply;

  socket.send(request);
//////////////////////////////////////////"""observe_line_2"""
   for (int request_nbr = 0; request_nbr != 1000; request_nbr++) 
   {
    socket.recv (&reply);
    std::cout << "Received World " << request_nbr << std::endl;
   }
   return 0;
}

Output After executing Reqply then executing request then following error occurs

terminate called after throwing an instance of 'zmq::error_t'
  what():  Operation cannot be accomplished in current state
Aborted

Point to be observed

when "observe_line_1" is inside the for loop below it and "observe_line_2" is inside while loop below it and executed then the code is executed succesfully without any errors ????


Solution

  • Sending multiple replies for one request is not allowed by the REQ-REP model.

    The REQ-REP socket pair is in lockstep. The client issues zmq_send() and then zmq_recv(), in a loop (or once if that's all it needs). Doing any other sequence (e.g., sending two messages in a row) will result in a return code of -1 from the send or recv call. Similarly, the service issues zmq_recv() and then zmq_send() in that order, as often as it needs to.

    reference, alternative socket types, maybe this can help