libcluon  0.0.148
cluon::UDPReceiver Class Reference

#include <UDPReceiver.hpp>

Public Member Functions

 UDPReceiver (const std::string &receiveFromAddress, uint16_t receiveFromPort, std::function< void(std::string &&, std::string &&, std::chrono::system_clock::time_point &&)> delegate, uint16_t localSendFromPort=0) noexcept
 
 ~UDPReceiver () noexcept
 
bool isRunning () const noexcept
 

Detailed Description

To receive data from a UDP socket, simply include the header #include <cluon/UDPReceiver.hpp>.

Next, create an instance of class cluon::UDPReceiver as follows: cluon::UDPReceiver receiver("127.0.0.1", 1234, delegate);. The first parameter is of type std::string expecting a numerical IPv4 address, the second parameter specifies the UDP port, from which data shall be received from, and the last parameter is of type std::function that is called whenever new bytes are available to be processed.

The complete signature for the delegate 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. An example using a C++ lambda expression would look as follows:

cluon::UDPReceiver receiver("127.0.0.1", 1234,
[](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(&timestamp), "%Y-%m-%d %X")
<< ", containing '" << data << "'." << std::endl;
});

After creating an instance of class cluon::UDPReceiver, 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.

A complete example is available here.

Constructor & Destructor Documentation

◆ UDPReceiver()

cluon::UDPReceiver::UDPReceiver ( const std::string &  receiveFromAddress,
uint16_t  receiveFromPort,
std::function< void(std::string &&, std::string &&, std::chrono::system_clock::time_point &&)>  delegate,
uint16_t  localSendFromPort = 0 
)
noexcept

Constructor.

Parameters
receiveFromAddressNumerical IPv4 address to receive UDP packets from.
receiveFromPortPort to receive UDP packets from.
delegateFunctional (noexcept) to handle received bytes; parameters are received data, sender, timestamp.
localSendFromPortPort that an application is using to send data. This port (> 0) is ignored when data is received.

References cluon::getIPv4FromHostname(), and retVal.

◆ ~UDPReceiver()

cluon::UDPReceiver::~UDPReceiver ( )
noexcept

References retVal.

Member Function Documentation

◆ isRunning()

bool cluon::UDPReceiver::isRunning ( ) const
noexcept