This library is header only. The user must include the header file and add the dependency to the manifest.
Include the main header for the library.
Add to the manifest the dependency.
The main class is based on the boost::asio library, before usage the user should be acquainted with the naming scheme of the boost library. Link to library http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio.html.
The boost tcp communication relies on a input/output service. The user must declare the service using as:
The service constructor has no arguments. With the service declared the user must declare the AsyncClient class.
The class constructor receives the io service, the server ip and port (both as std::string). Once the constructor is called the class will schedule a connection attempt.
The user may specify a connection event handler. This function will be asynchronously called once a successful connection is established.
In this example the class method connectionHandler will be used, the boost::bind is used to link a class method with the class instance handler_class_instance.
The connectHandler member of the AsyncClient is a boost::signal slot, it also supports non-member functions.
The user can also specify a receive data event handler. This function will be asynchronously called once a complete line is available (terminated with \n by default, see the AsyncClient class constructor documentation for additions details on how to change this behavior).
The final step to initialize the communication is to run the io service. this can be achieved by calling the run method on the io_service instance. Since we are talking about asynchronously communication the best practice is to run this method on a separate thread, using, by example, boost::thread:
Once the tread is launched the process continuously tries to establish a connection to the server. If the connection is lost, the class schedules a new reconnection attempt.
To write to the server the user can simply call:
This functions receives a std::string as input and schedules an asynchronous write request.
The io service can be closed asynchronously from another thread by calling:
An to join the asynchronous thread:
This example, due to the extra boost functions, requires additional includes: