/** @file * @brief TcpIpHelper class implementation. This class represents a Helper to easily perform tcp/ip operations. * * * * @copyright Intra2net AG * @license GPLv2 */ #include "net_helper.hpp" #include "tcp_service.hpp" using namespace std; /** * Default Constructor. */ NetHelper::NetHelper() : Log(new Logger()) { IPServicePtr = IPService::Ptr(new TCPService()); } /** * Constructor. * @param _log Logger */ NetHelper::NetHelper( const Logger::Ptr _log ) : Log(_log) { IPServicePtr = IPService::Ptr(new TCPService()); } /** * Default destructor */ NetHelper::~NetHelper() { } /** * Open the connection to the peer. * @return 0 if all is fine, -1 on error. */ int NetHelper::open_connection(const string& hostname, const string& port) const { try { IPServicePtr->connect(hostname,port); } catch ( const boost::system::system_error& boost_exception ) { ostringstream out; out << "NetHelper::open_connection(): " << boost_exception.what() << " Host: " << hostname << " Port: " << port; Log->print_network_error(out.str()); return -1; } catch ( const exception& e ) { ostringstream out; out << "NetHelper::open_connection(): " << e.what() << " Host: " << hostname << " Port: " << port; Log->print_network_error(out.str()); return -1; } catch ( ... ) { ostringstream out; out << "Unknown exception caught while trying to connect to Host: " << hostname << " Port: " << port; Log->print_network_error(out.str()); return -1; } return 0; } /** * Send the given data * @param data Data to send * @return 0 if all is fine, -1 on error. */ int NetHelper::send_data(const std::string& data) const { try { IPServicePtr->write_to_socket(data); } catch ( const boost::system::system_error& boost_exception ) { ostringstream out; out << "NetHelper::send_data(): " << boost_exception.what() << " Data to be send: " << data; Log->print_network_error(out.str()); return -1; } return 0; } /** * Receive all available data from the peer. * @return The data received. */ std::string NetHelper::receive_data() const { string received_data; try { received_data = IPServicePtr->read_from_socket(); } catch ( const boost::system::system_error& boost_exception ) { ostringstream out; out << "NetHelper::receive_data(): " << boost_exception.what(); Log->print_network_error(out.str()); return ""; } return received_data; } /** * Close the active session. * @return 0 if all is fine, -1 on error */ int NetHelper::close_connection() const { try { IPServicePtr->close(); } catch ( const boost::system::system_error& boost_exception ) { ostringstream out; out << "NetHelper::close_connection(): " << boost_exception.what(); Log->print_network_error(out.str()); return -1; } return 0; }