Skip to content
Salvo Virga edited this page Sep 20, 2018 · 5 revisions
Example for Request / Reply

The Request / Reply pattern is implemented using the classes Client and Server.
A Client sends a request while a Server will receive requests and reply with an answer.
In simple, both a request and a reply are contained in the same message.

In the following example code, a Client sends a request with a simple_msgs::Point and receive the point being increased by one.

This is of course a trivial example, for a real example imagine a message that contains a simple_msgs::Point and a simple_msgs::Bool :

simple_msgs::Point request
simple_msgs::Bool reply

When the message is sent the request (the point) is filled with some value, the reply (the boolean) is set to 'false'.
A reply from the Server would contain the same point and the boolean set to 'true', to indicate that the message has been received.

This is, again, just an example, but it can be a good idea to have separated fields for the request and the reply.

Mind that any new custom defined message, could include one or more message defined in simple_msgs as well as native Flatbuffers types (int, double, etc.). A good example is how simple_msgs::Image is defined.

Here is the example with a simple_msgs::Point sent as request and sent back increased by one as reply. A Client will send 10 requests to a Server using its ip address and port.

int main()
{
  simple_msgs::Point p{5.0, 6.0, 7.0};

  simple::Client<simple_msgs::Point> client{"tcp://IP_ADDRESS:5555"};

  for (auto i = 0; i < 10; ++i)
  {
    if (client.request(p))
    {
      std::cout << "Request successful \n" << p << std::endl;
    }
    else
    {
      std::cerr << "Request to the server failed." << std::endl;
    }
    // Sleep for some time.
  }
}

Here a Server will wait for requests sent from any Client on its port.
Any request is processed using the given callback function, in this case the received point is just increased by one.

void example_callback(simple_msgs::Point& p)
{
  std::cout << "Received a point. Adding 1 to its elements." << std::endl;
  p += 1.0;
}

int main()
{
  simple::Server<simple_msgs::Point> server{"tcp://*:5555", example_callback};
}

A full example is available for a Client and a Server.

Clone this wiki locally