To exchange data via TCP, simply include the header #include <cluon/TCPConnection.hpp>
.
Next, create an instance of class cluon::TCPConnection
as follows: cluon::TCPConnection connection("127.0.0.1", 1234, newDataDelegate, connectionLostDelegate);
. The first parameter is of type std::string
expecting a numerical IPv4 address, the second parameter specifies the TCP port, from which data shall be received from, the third paraemter is of type std::function
that is called whenever new bytes are available to be processed, and the last parameter is of type std::function
that is called when the connection is lost.
The complete signature for the newDataDelegate function is std::function<void(std::string &&, std::string &&, std::chrono::system_clock::time_point &&) noexcept>
: The first parameter contains the bytes that have been received, the second parameter containes the human-readable representation of the sender (X.Y.Z.W:ABCD), and the last parameter is the time stamp when the data has been received.
The complete signature for the connectionLostDelegate function is std::function<void() noexcept>
.
To finally send data, simply call the method send
supplying the data to be sent: connection.send(std::move("Hello World!")
. Please note that the data is supplied using the move-semantics. The method send
returns a std::pair<ssize_t, int32_t>
where the first element returns the size of the successfully sent bytes and the second element contains the error code in case the transmission of the data failed.
An example using a C++ lambda expression would look as follows:
[](std::string &&data, std::string &&sender, std::chrono::system_clock::time_point &&ts) noexcept {
const auto timestamp(std::chrono::system_clock::to_time_t(ts));
std::cout << "Received " << data.size() << " bytes"
<< " from " << sender
<< " at " << std::put_time(std::localtime(×tamp), "%Y-%m-%d %X")
<< ", containing '" << data << "'." << std::endl;
},
[](){ std::cout << "Connection lost." << std::endl; });
std::pair<ssize_t, int32_t>
retVal = connection.send(std::move(
"Hello World!"));
After creating an instance of class cluon::TCPConnection
, it is immediately activated and concurrently waiting for data in a separate thread. To check whether the instance was created successfully and running, the method isRunning()
should be called.