00001 /////////////////////////////////////////////////////////////////////////////////////////////// 00002 /*! \file ClientSocket.cpp 00003 * \brief Implementation of the ClientSocket class for communicating to a server program. 00004 * 00005 * The socket communications classes are based on the tutorial entitled 00006 * "Linux Socket Programming In C++" by Rob Tougher on the Linux Gazette 00007 * website. ( http://linuxgazette.net/issue74/tougher.html ) 00008 * 00009 * \author Scott A. Kowalchuk 00010 * \date 2006/11/29 00011 *///////////////////////////////////////////////////////////////////////////////////////////// 00012 /* 00013 * \Status 00014 * 00015 * 00016 */ 00017 ///////////////////////////////////////////////////////////////////////////////////////////// 00018 00019 #include "ClientSocket.h" 00020 #include "SocketException.h" 00021 00022 /*! \brief Client Socket constructor. 00023 * 00024 */ 00025 ClientSocket::ClientSocket( ) 00026 { 00027 } 00028 00029 /*! \brief Create client socket and connect to server. 00030 * 00031 * @param host is the IP address (xxx.xxx.xxx.xxx) or host name (vt.edu) of the server 00032 * @param port is the open port on the server 00033 * @return throw SocketException if error 00034 */ 00035 ClientSocket::ClientSocket( std::string host, int port ) 00036 { 00037 Connect( host, port ); 00038 00039 } 00040 00041 /*! \brief Client Socket constructor. 00042 * 00043 */ 00044 ClientSocket::~ClientSocket( ) 00045 { 00046 } 00047 00048 /*! \brief Create client socket and connect to server. 00049 * 00050 * @param host is the IP address (xxx.xxx.xxx.xxx) or host name (vt.edu) of the server 00051 * @param port is the open port on the server 00052 * @return throw SocketException if error 00053 */ 00054 void ClientSocket::Connect( std::string host, int port ) 00055 { 00056 if ( ! Socket::create() ) 00057 { 00058 throw SocketException ( "Could not create client socket." ); 00059 } 00060 00061 if ( ! Socket::connect ( host, port ) ) 00062 { 00063 throw SocketException ( "Could not bind to port." ); 00064 } 00065 00066 } 00067 00068 /*! \brief Send string to server. 00069 * 00070 * @param str sting of data to send 00071 * @return throw SocketException if error 00072 */ 00073 const ClientSocket& ClientSocket::operator << ( const std::string& str ) const 00074 { 00075 if ( ! Socket::send ( str ) ) 00076 { 00077 throw SocketException ( "Could not write to socket." ); 00078 } 00079 00080 return *this; 00081 00082 } 00083 00084 00085 /*! \brief Receiver string from server. 00086 * 00087 * @param str sting of data to send 00088 * @return throw SocketException if error 00089 */ 00090 const ClientSocket& ClientSocket::operator >> ( std::string& str ) const 00091 { 00092 if ( ! Socket::recv ( str ) ) 00093 { 00094 throw SocketException ( "Could not read from socket." ); 00095 } 00096 00097 return *this; 00098 } 00099