SockIt
Public Member Functions | Protected Member Functions | Protected Attributes | Static Protected Attributes | Friends

Udp Class Reference

#include <Udp.h>

Inheritance diagram for Udp:
UdpClient UdpServer

List of all members.

Public Member Functions

 Udp (string host, int port, boost::asio::io_service &io_service)
virtual ~Udp ()

Protected Member Functions

string bool_option_to_string (optional< bool > &arg, string iftrue, string iffalse)
template<class T >
string option_to_string (optional< T > &arg)
void parse_string_bool_arg (map< string, string > &options, string arg, optional< bool > &arg_value)
void parse_args (map< string, string > options)
void log_options ()
virtual void listen ()=0
virtual void close ()=0
void send_handler (const boost::system::error_code &err, std::size_t bytes_transferred, string msg, string host, int port)
void receive_handler (const boost::system::error_code &err, std::size_t bytes_transferred, boost::shared_ptr< udp::socket > socket, boost::shared_ptr< udp::endpoint > endpoint, string host, int port)
virtual void fire_error_event (const string &message)=0
virtual void fire_data_event (const string data, boost::shared_ptr< udp::socket > socket, boost::shared_ptr< udp::endpoint > endpoint)=0

Protected Attributes

boost::asio::io_service & io_service
boost::array< char, BUFFER_SIZEreceive_buffer
int pending_sends
boost::mutex pending_sends_mutex
bool should_close
optional< bool > using_ipv6
optional< bool > multicast
optional< string > multicast_group
optional< int > multicast_ttl
optional< bool > do_not_route
optional< bool > reuse_address
string host
int port
boost::shared_ptr< udp::endpoint > remote_endpoint
bool failed

Static Protected Attributes

static const int BUFFER_SIZE = 2048

Friends

class UdpEvent

Detailed Description

Interface to abstract out the client-server model for use in the Event. Contains common handlers used by both UDP servers and clients.

See also:
Event

Definition at line 39 of file Udp.h.


Constructor & Destructor Documentation

Udp::Udp ( string  host,
int  port,
boost::asio::io_service &  io_service 
)

Builds a generic UDP object, and registers the 'shutdown' method on the API.

Parameters:
hostThe hostname for this UDP object. For clients, this represents the remote host's hostname, and for servers, defaults to 'localhost'.
portThe port for this UDP object, which for clients, represents the port of the remote host to which to connect, and for servers, represents the port to which to bind and listen for incoming connections.
io_serviceThe I/O service used for asynchronous I/O requests

Definition at line 10 of file Udp.cpp.

References remote_endpoint.

                                                                :
    host(host), port(port), pending_sends(0), should_close(false), io_service(io_service), failed(false)
{
    remote_endpoint = boost::shared_ptr<udp::endpoint>(new udp::endpoint());
}
virtual Udp::~Udp ( ) [inline, virtual]

Immediately calls the close function, freeing all resources for this UDP object and shutting down any open connections.

Definition at line 59 of file Udp.h.

{}

Member Function Documentation

string Udp::bool_option_to_string ( optional< bool > &  arg,
string  iftrue,
string  iffalse 
) [inline, protected]

Helper for logging options passed in.

Parameters:
argoptional bool option
iftrueif the arg has been set to true, return this
iffalseif the arg hasn't been set, or is set to false, return this

Definition at line 143 of file Udp.cpp.

Referenced by log_options().

{
    if (arg && *arg)
        return iftrue;
    return iffalse;
}
virtual void Udp::close ( ) [protected, pure virtual]

Immediately frees all resources for this UDP object and shutting down any open connections. This function should never be invoked by the base class, and logs an error if this ever occurs.

Implemented in UdpClient, and UdpServer.

Referenced by send_handler().

virtual void Udp::fire_data_event ( const string  data,
boost::shared_ptr< udp::socket >  socket,
boost::shared_ptr< udp::endpoint >  endpoint 
) [protected, pure virtual]

Helper to fire data event to javascript.

Parameters:
dataThe data received
socketThe socket on which to reply to this data
endpointThe connected endpoint to the remote host

Implemented in UdpClient, and UdpServer.

Referenced by receive_handler().

virtual void Udp::fire_error_event ( const string &  message) [protected, pure virtual]

Helper to fire an error event to javascript.

Parameters:
messageThe error message

Implemented in UdpClient, and UdpServer.

Referenced by receive_handler(), and send_handler().

virtual void Udp::listen ( ) [protected, pure virtual]

Helper function to listen for incoming data.

Implemented in UdpClient, and UdpServer.

Referenced by receive_handler().

void Udp::log_options ( ) [protected]

Write to the log the options used to create this connection.

Definition at line 158 of file Udp.cpp.

References bool_option_to_string(), do_not_route, host, Logger::info(), multicast, multicast_group, multicast_ttl, port, reuse_address, and using_ipv6.

Referenced by UdpClient::init_socket(), and UdpServer::initialize().

{
    string options("These arguments were passed in: ");

    options.append(bool_option_to_string(using_ipv6, "ipv6, ", "ipv4, "));
    options.append(bool_option_to_string(multicast, "multicast enabled, ", "multicast disabled, "));
    options.append(bool_option_to_string(do_not_route, "no routing, ", "use routing, "));
    options.append(bool_option_to_string(reuse_address, "reuse address, ", "don't reuse address, "));

    options.append("multicast group: ");
    options.append(option_to_string<string> (multicast_group));

    options.append(", multicast ttl: ");
    options.append(option_to_string<int> (multicast_ttl));

    Logger::info(options, port, host);
}
template<class T >
string Udp::option_to_string ( optional< T > &  arg) [inline, protected]

Helper for logging options passed in.

Parameters:
argthe optional argument

Definition at line 151 of file Udp.cpp.

{
    if (arg)
        return boost::lexical_cast<string>(*arg);
    return string("unset");
}
void Udp::parse_args ( map< string, string >  options) [protected]

Parses any options (like whether or use IPv6 or IPv4) from the options. Supported options currently include:

ipv6 if true, use ipv6. otherwise use ipv4. multicast enable udp multicasting multicast group the multicast group to join multicast ttl number of multicast hops to make; do not route prevent routing, use local interfaces reuse address allow the socket to bind to an address already in use keep alive allow the socket to send keep-alives.

Parameters:
optionsA map of options to values.

Definition at line 107 of file Udp.cpp.

References do_not_route, multicast, multicast_group, multicast_ttl, parse_string_bool_arg(), reuse_address, and using_ipv6.

Referenced by UdpClient::UdpClient(), and UdpServer::UdpServer().

{
    map<string, string>::iterator it;
    map<string, string> transformed_options;

    string t("true");
    string f("false");

    // transform the entire map to lower case
    for (it = options.begin(); it != options.end(); it++)
    {
        string k = it->first;
        string v = it->second;

        std::transform(k.begin(), k.end(), k.begin(), ::tolower);
        std::transform(v.begin(), v.end(), v.begin(), ::tolower);

        k.erase(std::remove_if(k.begin(), k.end(), ::isspace), k.end());
        v.erase(std::remove_if(v.begin(), v.end(), ::isspace), v.end());

        transformed_options.insert(std::pair<string, string>(k, v));
    }

    /* Lets just pretend you didn't see any of this */
    parse_string_bool_arg(transformed_options, "ipv6", using_ipv6);
    parse_string_bool_arg(transformed_options, "multicast", multicast);
    parse_string_bool_arg(transformed_options, "donotroute", do_not_route);
    parse_string_bool_arg(transformed_options, "reuseaddress", reuse_address);

    if ((it = transformed_options.find("multicastgroup")) != transformed_options.end())
        multicast_group.reset(it->second);

    if ((it = transformed_options.find("multicastttl")) != transformed_options.end())
        multicast_ttl.reset(boost::lexical_cast<int>(it->second));
}
void Udp::parse_string_bool_arg ( map< string, string > &  options,
string  arg,
optional< bool > &  arg_value 
) [inline, protected]

Helper for parsing arguments

Parameters:
optionsA map of strings to string representing the options passed in and their values
argThe specific option to check for
arg_valueThis will hold the value of the argument, if found.

Definition at line 94 of file Udp.cpp.

Referenced by parse_args().

{
    map<string, string>::iterator it;

    if ((it = options.find(arg)) != options.end())
    {
        if (it->second == std::string("true"))
            arg_value.reset(true);
        if (it->second == std::string("false"))
            arg_value.reset(false);
    }
}
void Udp::receive_handler ( const boost::system::error_code &  err,
std::size_t  bytes_transferred,
boost::shared_ptr< udp::socket >  socket,
boost::shared_ptr< udp::endpoint >  endpoint,
string  host,
int  port 
) [protected]

Handler invoked when some data has been received.

Parameters:
errThe error code encountered when trying to receive data, if any occurred. On success, this value is zero, and nonzero on error.
bytes_transferredThe number of bytes successfully received over the connection.
socketThe connection on which attempted to receive data.
endpointThe connected endpoint to the remote host
hostThe hostname for this UDP object
portThe port for this UDP object

Definition at line 59 of file Udp.cpp.

References Logger::error(), fire_data_event(), fire_error_event(), Logger::info(), listen(), receive_buffer, and should_close.

Referenced by UdpServer::listen(), and UdpClient::listen().

{
    // Check for errors
    if (error_code)
    {
        if (error_code == boost::asio::error::operation_aborted)
        {
            Logger::info("UDP receive failed, aborted", port, host);
        }
        else
        {
            string message(
                    "UDP receive failed, error message: '" + error_code.message() + "', code: '" + boost::lexical_cast<string>(
                            error_code.value()) + "'");
            Logger::error(message, port, host);
            fire_error_event(message);
        }

        return;
    }

    // Get the data && fire a data event
    string data(receive_buffer.c_array(), bytes_transferred);
    fire_data_event(data, socket, endpoint);

    // Pull out the data we received, and fire a data received event
    Logger::info("UDP receive succeeded, received " + boost::lexical_cast<string>(bytes_transferred) + " bytes, data is: " + data, port,
            host);

    // Listen for more messages if we're not trying to close down this UDP object
    if (!should_close)
        listen();
}
void Udp::send_handler ( const boost::system::error_code &  err,
std::size_t  bytes_transferred,
string  msg,
string  host,
int  port 
) [protected]

Handler invoked when the data has been sent (or sending terminated in error).

Parameters:
errThe error code encountered when trying to send data, if any occurred. On success, this value is zero, and nonzero on error.
bytes_transferredThe number of bytes successfully sent over the connection.
msgThe data to be sent.
hostThe hostname for this UDP object
portThe port for this UDP object

Definition at line 16 of file Udp.cpp.

References close(), Logger::error(), fire_error_event(), Logger::info(), pending_sends, pending_sends_mutex, and should_close.

Referenced by UdpEvent::send(), and UdpClient::send().

{
    if (error_code)
    {
        if (error_code == boost::asio::error::operation_aborted)
        {
            Logger::info("UDP send failed, aborted", port, host);
        }
        else
        {
            string message(
                    "UDP send failed, error message: '" + error_code.message() + "', error code '" + boost::lexical_cast<string>(
                            error_code.value()) + "' was encountered");
            Logger::error(message, port, host);
            fire_error_event(message);
        }
        return;
    }

    // Did not successfully send all the data, don't try and resend the rest (this is UDP)
    if (bytes_transferred != data.size())
    {
        string message(
                string("UDP send failed, data was not successfully sent, only ") + boost::lexical_cast<string>(bytes_transferred) + " of "
                        + boost::lexical_cast<string>(message.size()) + " total bytes were sent");
        Logger::error(message, port, host);
        fire_error_event(message);

        return;
    }

    string message("UDP send succeeded, sent " + boost::lexical_cast<string>(bytes_transferred) + " bytes, message is: " + data);
    Logger::info(message, port, host);

    pending_sends_mutex.lock();
    pending_sends--; // just handled sending
    int pending_sends_now = pending_sends;
    pending_sends_mutex.unlock();

    if (pending_sends_now == 0 && should_close)
        close();
}

Friends And Related Function Documentation

friend class UdpEvent [friend]

Reimplemented in UdpServer.

Definition at line 61 of file Udp.h.


Member Data Documentation

const int Udp::BUFFER_SIZE = 2048 [static, protected]

A constant representing the size of the buffer in which to receive data. This is adjust to support the largest packet possible according to the UDP protocol.

Definition at line 171 of file Udp.h.

Referenced by UdpClient::init_socket(), and UdpServer::initialize().

optional<bool> Udp::do_not_route [protected]

Flag to prevent routing, use local interfaces only

Definition at line 198 of file Udp.h.

Referenced by UdpClient::init_socket(), UdpServer::initialize(), log_options(), and parse_args().

bool Udp::failed [protected]

A flag to say if this UDP object has permanently failed and cannot continue for some reason or another

Definition at line 213 of file Udp.h.

Referenced by UdpEvent::send(), UdpClient::send(), UdpServer::shutdown(), UdpClient::shutdown(), UdpServer::start_listening(), and UdpClient::UdpClient().

string Udp::host [protected]

The hostname for this UDP object ('SERVER' for servers, or the hostname of the remote host for clients)

Definition at line 204 of file Udp.h.

Referenced by UdpClient::get_host(), UdpClient::init_socket(), UdpServer::initialize(), UdpServer::listen(), UdpClient::listen(), log_options(), UdpClient::resolve_handler(), UdpClient::send(), UdpServer::shutdown(), and UdpServer::start_listening().

boost::asio::io_service& Udp::io_service [protected]

The I/O service for perform nonblocking actions

Definition at line 167 of file Udp.h.

optional<bool> Udp::multicast [protected]

Flag representing whether or not multicast is enabled for this UDP object.

Definition at line 189 of file Udp.h.

Referenced by UdpClient::init_socket(), UdpServer::initialize(), log_options(), parse_args(), and UdpServer::start_listening().

optional<string> Udp::multicast_group [protected]

If multicast is enabled, use this for the group to join

Definition at line 192 of file Udp.h.

Referenced by log_options(), parse_args(), and UdpServer::start_listening().

optional<int> Udp::multicast_ttl [protected]

If multicast is enabled, this is the TTL or hops

Definition at line 195 of file Udp.h.

Referenced by UdpClient::init_socket(), UdpServer::initialize(), log_options(), and parse_args().

int Udp::pending_sends [protected]

The number of asynchronous I/O requests that are pending completion

Definition at line 177 of file Udp.h.

Referenced by UdpEvent::send(), UdpClient::send(), send_handler(), UdpServer::shutdown(), and UdpClient::shutdown().

boost::mutex Udp::pending_sends_mutex [protected]

Mutex for accessing the number of pending sends

Definition at line 180 of file Udp.h.

Referenced by UdpClient::send(), send_handler(), and UdpClient::shutdown().

int Udp::port [protected]

The port (the port bound to by servers, port on which to connect to the remote host for clients)

Definition at line 207 of file Udp.h.

Referenced by UdpServer::get_port(), UdpClient::get_port(), UdpClient::init_socket(), UdpServer::initialize(), UdpServer::listen(), UdpClient::listen(), log_options(), UdpClient::resolve_handler(), UdpClient::send(), UdpServer::shutdown(), and UdpServer::start_listening().

boost::array<char, BUFFER_SIZE> Udp::receive_buffer [protected]

A buffer for receiving data from the remote host.

Definition at line 174 of file Udp.h.

Referenced by UdpServer::listen(), UdpClient::listen(), and receive_handler().

boost::shared_ptr<udp::endpoint> Udp::remote_endpoint [protected]

A connected endpoint to the remote host.

Definition at line 210 of file Udp.h.

Referenced by UdpServer::listen(), UdpClient::listen(), UdpClient::resolve_handler(), UdpClient::send(), and Udp().

optional<bool> Udp::reuse_address [protected]

Flag to allow the socket to be bound to an address that is already in use.

Definition at line 201 of file Udp.h.

Referenced by UdpClient::init_socket(), UdpServer::initialize(), log_options(), and parse_args().

bool Udp::should_close [protected]

A flag indicating whether or not this object has been requested to shutdown.

Definition at line 183 of file Udp.h.

Referenced by UdpClient::close(), UdpClient::fire_data_event(), UdpClient::fire_error_event(), receive_handler(), UdpClient::send(), send_handler(), UdpServer::shutdown(), and UdpClient::shutdown().

optional<bool> Udp::using_ipv6 [protected]

Flag for using IPv6, if true, this UDP object uses IPv6, otherwise, it is using IPv4.

Definition at line 186 of file Udp.h.

Referenced by UdpClient::init_socket(), UdpServer::initialize(), log_options(), parse_args(), UdpClient::send(), and UdpServer::start_listening().


The documentation for this class was generated from the following files:
 All Classes Files Functions Variables Typedefs Friends Defines