void CClient::send_message( const std::string& strMsg )
{
if( send( m_iFlIndCli, strMsg.c_str(), SZBUFF, 0 ) < 0 )
_error( "Can not send message to connected server!" );
if( !_receive_from_server() ) exit( 1 );
}//
bool CClient::_bind()
{
if( bind( m_iFlIndCli, ( TSOCKADDR* )&m_addrCli, sizeof( m_addrCli ) ) < 0 )
{
_error( "Can't bind to the computer(client)!" );
close( m_iFlIndCli );
return false;
}//
return true;
}//
bool CClient:: _socket()
{
if( ( m_iFlIndCli = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
{
_error( "Can't create a sock at this client!" );
return false;
}
return true;
}//
void CClient::_write_log( const char* sz )
{
try
{
long tmsp = time( NULL );
///ctime( &tmsp );
char szFileName[ SZBUFF ];
sprintf( szFileName, "%i.log", tmsp );
ofstream of( szFileName );
of<<sz<<endl<<endl;
cout<<"A log file is created... ..."<<endl;
of.close();
}
catch( exception& e )
{
_error( const_cast<char*>( e.what() ) );
}
}//
bool CClient::_receive_from_server()
{
char szRet[ SZBUFF ];
if( recv( m_iFlIndCli, szRet, SZBUFF, 0 ) < 0 )
{
_error( "Can't receive data from the asked server!" );
close( m_iFlIndCli );
return false;
}
if( m_fpGuiOutput )
m_fpGuiOutput( szRet );
cout<<"==================================="<<endl
<<"Receive from server"<<endl
<<"==================================="<<endl
<<szRet<<endl
<<"==================================="<<endl;
_write_log( szRet );
return true;
}//
bool CClient::_connect()
{
socklen_t iLen = sizeof( m_addrSer );
///if( connect( m_iFlIndCli, ( TSOCKADDR* )&m_addrCli, iLen ) < 0 )
if( connect( m_iFlIndCli, ( TSOCKADDR* )&m_addrSer, iLen ) < 0 )
{
_error( "The client can't connect to the server!" );
close( m_iFlIndCli );
return false;
}
return true;
}//
void CClient::_init( const string& strIP, int iSerPort, int iCliPort )
{
if( !_socket() ) exit( 1 );
///
///configure for target server
///
memset( &m_addrSer, 0, sizeof( m_addrSer ) );
m_addrSer.sin_family = AF_INET;
inet_aton( strIP.c_str(), &m_addrSer.sin_addr );
m_addrSer.sin_port = htons( iSerPort );
///
///configure for local client who sends msg to the server
///this is not necessary done, because the port could not be always fixed.
///
memset( &m_addrCli, 0, sizeof( m_addrCli ) );
m_addrCli.sin_family = AF_INET;
m_addrCli.sin_port = htons( iCliPort );
m_addrCli.sin_addr.s_addr = htons( INADDR_ANY );
if( !_bind() ) exit( 1 );
if( !_connect() ) exit( 1 );
///if( !_receive_from_server() ) exit( 1 );
}//
CClient::CClient( const string& strIP, int iSerPort, int iCliPort, FPOUTPUT fpGuiOutput )
:m_fpGuiOutput( fpGuiOutput ),
m_iFlIndSer( 0 ),
m_iFlIndCli( 0 )
{
_init( strIP, iSerPort, iCliPort );
}//
CClient::~CClient(){ close( m_iFlIndCli ); }//