TcpLib
Loading...
Searching...
No Matches
MyTestServer Class Reference

An example class for a simple server derived from Server. More...

#include <MyTestServer.h>

Inheritance diagram for MyTestServer:
Collaboration diagram for MyTestServer:

Public Member Functions

 MyTestServer (unsigned int uiPort, int iAdressFamily, int iSocketType, int iProtocol, unsigned int uiDataSize, unsigned long ulMaxClients, int iSecTimeOut)
 
virtual ~MyTestServer ()
 
virtual void processClientMessage (tcp::AbstractMessage *pTcpMessage)
 
int sendToAllClients (std::string strMsg)
 
- Public Member Functions inherited from tcp::Server
 Server (unsigned int uiPort, int iAdressFamily, int iSocketType, int iProtocol, unsigned int uiDataSize, unsigned long ulMaxClients, int iSecTimeOut)
 
virtual ~Server ()
 
virtual void cancel () override
 
int acceptClientMessage (AbstractMessage *pTcpMessage)
 
- Public Member Functions inherited from tcp::TcpMain
 TcpMain (unsigned int uiPort, int iAdressFamily, int iSocketType, int iProtocol, int iSecTimeOut)
 
 TcpMain (unsigned int uiPort, int iAdressFamily, int iSocketType, int iProtocol, unsigned int uiDataSize, int iSecTimeOut)
 
virtual ~TcpMain ()
 
unsigned int getPortNum () const
 
virtual void setDataSize (unsigned int uiDataSize)
 
unsigned int getDataSize () const
 
SOCKET getMainSocket () const
 
void setTimeOutSec (int iSecTimeOut)
 
int TimeOutSec ()
 
- Public Member Functions inherited from eut::RepeatingThread
 RepeatingThread ()
 
virtual ~RepeatingThread ()
 
virtual int start ()
 
bool testCancel ()
 
RepeatingThread::STATUS status () const
 
bool isInExclusiveAccess () const
 
void setExclusiveAccess ()
 
void unsetExclusiveAccess ()
 
int getBreakCounter ()
 
virtual void takeABreak ()
 
virtual void finishBreak ()
 
void waitForInput ()
 
void signalInput ()
 

Protected Member Functions

 MyTestServer ()
 
 MyTestServer (unsigned int, int, int, int, int)
 
 MyTestServer (unsigned int, int, int, int, unsigned int, int)
 
virtual void insertNewClient (Server::ServerReceiverTransmitter *pNewServerReceiverTransmitter)
 
- Protected Member Functions inherited from tcp::Server
 Server ()
 
 Server (unsigned int, int, int, int, int)
 
 Server (unsigned int, int, int, int, unsigned int, int)
 
virtual void work () override
 
virtual void insertNewClient (Server::ServerReceiverTransmitter *pNewServerReceiverTransmitter)
 
Server::ServerReceiverTransmittergetClient (SOCKET Socket)
 
virtual int removeClient (SOCKET Socket)
 
virtual Server::ServerReceiverTransmittergenerateNewServerReceiverTransmitter (Server *pParent, SOCKET Socket, unsigned int iDataSize) const
 
void setClientMapReceiverValid (bool bValid)
 
void clearClientMap ()
 
unsigned long getMaxClients () const
 
virtual int send (SOCKET ClientSocket, char *pszRawMsg, unsigned int uiRawMsgSize, unsigned int uiMessageID=0, int iActionCode=0, const std::string &rstrInfo="")
 
virtual int send (Message *pTcpMessage) override
 
- Protected Member Functions inherited from tcp::TcpMain
 TcpMain ()
 
void setWSACleanup () const
 
int startWinsock () const
 
- Protected Member Functions inherited from eut::RepeatingThread
void threadWork ()
 
void setStatus (STATUS eStatus)
 
STATUS getStatus ()
 
void toOrder (ORDER eOrder)
 
ORDER getOrder ()
 

Private Member Functions

 MyTestServer (const MyTestServer &)
 
MyTestServeroperator= (const MyTestServer &)
 

Additional Inherited Members

- Public Types inherited from eut::RepeatingThread
enum  EuTHREADERROR { EuTHREAD_ERR_NO_THREAD = -10301 , EuTHREAD_ERR_THREAD_ALREADY_WORKING = -10302 , EuTHREAD_ERR_THREAD_BREAK_COUNT_LESS_THAN_ZERO = -10303 , EuTHREAD_ERR_UNKNOWN = -10400 }
 Error range = -10301 to -10400 More...
 
enum  STATUS {
  eAT_THE_START , eWORKING , ePAUSING , eENDING ,
  eCOMPLETED
}
 
enum  ORDER { eUNDEFINED , eDO_WORK , eEXIT }
 
- Protected Attributes inherited from tcp::Server
ServerAcceptReceiverm_pAcceptReceiver
 
std::map< SOCKET, ServerReceiverTransmitter *, std::less< SOCKET > > m_ClientMap
 
- Protected Attributes inherited from tcp::TcpMain
int m_iSecTimeOut
 
unsigned int m_uiServerPort
 
unsigned int m_uiDataSize
 
int m_iAdressFamily
 
int m_iSocketType
 
int m_iProtocol
 
SOCKET m_MainSocket
 

Detailed Description

An example class for a simple server derived from Server.

Messages from connected clients are output. Additionally, MyTestServer can send messages to all clients.

Implementation of MyTestServer:

MyTestServer.cpp

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#include "MyTestServer.h"
#include <iostream>
//-----------------------------------------------------------------------------
#define SUPER Server
//-----------------------------------------------------------------------------
: SUPER()
{
}
//-----------------------------------------------------------------------------
MyTestServer::MyTestServer( unsigned int uiPort,
int iAdressFamily,
int iSocketType,
int iProtocol,
int iSecTimeOut )
: SUPER( uiPort, iAdressFamily, iSocketType, iProtocol, iSecTimeOut )
{
}
//-----------------------------------------------------------------------------
MyTestServer::MyTestServer( unsigned int uiPort,
int iAdressFamily,
int iSocketType,
int iProtocol,
unsigned int uiDataSize,
int iSecTimeOut )
: SUPER( uiPort, iAdressFamily, iSocketType, iProtocol, uiDataSize, iSecTimeOut )
{
}
//-----------------------------------------------------------------------------
MyTestServer::MyTestServer( unsigned int uiPort,
int iAdressFamily,
int iSocketType,
int iProtocol,
unsigned int uiDataSize,
unsigned long ulMaxClients,
int iSecTimeOut )
: SUPER( uiPort, iAdressFamily, iSocketType, iProtocol, uiDataSize, ulMaxClients, iSecTimeOut )
{
}
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
{
tcp::Message * t_pTcpMessage = dynamic_cast<tcp::Message*>( pTcpMessage );
tcp::ServerMessage * t_pTcpServerMessage = dynamic_cast<tcp::ServerMessage*>( pTcpMessage );
tcp::ServerAcceptMessage * t_pTcpServerAcceptMessage = dynamic_cast<tcp::ServerAcceptMessage*>( pTcpMessage );
if ( t_pTcpServerMessage )
{
if ( t_pTcpServerMessage->getActionCode() < 0 )
{
std::cout << "server get error-msg from client[" << t_pTcpServerMessage->getSocket() <<"] with code [" << t_pTcpServerMessage->getActionCode() << "]" << std::endl;
}
else
{
std::cout << "server get client-msg from client[" << t_pTcpServerMessage->getSocket() << "] with code [" << t_pTcpServerMessage->getActionCode() << "]";
if ( t_pTcpServerMessage->getRawMsgSize() )
{
std::cout << " - " << t_pTcpServerMessage->getRawMsgPt();
}
std::cout << std::endl;
}
}
else if ( t_pTcpServerAcceptMessage )
{
std::cout << "new client:" << t_pTcpServerAcceptMessage->getSocket() << std::endl;
}
else if ( t_pTcpMessage )
{
std::cout << "Err! No message!" << std::endl;
}
if ( pTcpMessage ) SUPER::processClientMessage( pTcpMessage );
}
//-----------------------------------------------------------------------------
int MyTestServer::sendToAllClients( std::string strMsg )
{
int t_iErr = 0;
std::map< SOCKET, ServerReceiverTransmitter * >::iterator m_ClientMapIterator;
char * t_pchBuffer = 0;
tcp::Message * t_pTcpMessage = 0;
if ( m_ClientMap.size() > 0 )
{
for ( m_ClientMapIterator = m_ClientMap.begin();
m_ClientMapIterator != m_ClientMap.end();
m_ClientMapIterator++ )
{
t_pchBuffer = new char[ strlen( strMsg.c_str() ) + 1 ];
strcpy(t_pchBuffer, strMsg.c_str());
t_pchBuffer[ strlen( strMsg.c_str() ) ] = '\x00';
t_pTcpMessage = new tcp::Message( t_pchBuffer, strlen( strMsg.c_str() ) + 1, 0, 0, "" );
// int acceptOrder( Message * pTcpMessage );
t_iErr = (*m_ClientMapIterator).second->send( t_pTcpMessage );
}
}
return t_iErr;
}
//-----------------------------------------------------------------------------
void MyTestServer::insertNewClient( Server::ServerReceiverTransmitter * pNewServerReceiverTransmitter )
{
int t_iErr(0);
std::string t_sIPAdress;
unsigned int t_uiPort(0);
SUPER::insertNewClient( pNewServerReceiverTransmitter );
t_iErr = pNewServerReceiverTransmitter->getPeerName( t_sIPAdress, t_uiPort );
std::cout << "new client ip:" << t_sIPAdress << " port:" << t_uiPort << " err:" << t_iErr << std::endl;
}
//-----------------------------------------------------------------------------
#undef SUPER
//-----------------------------------------------------------------------------
Header for MyTestServer.
virtual void processClientMessage(tcp::AbstractMessage *pTcpMessage)
virtual ~MyTestServer()
int sendToAllClients(std::string strMsg)
virtual void insertNewClient(Server::ServerReceiverTransmitter *pNewServerReceiverTransmitter)
Base class for messages which can be sent, received and processed by the Tcp-classes.
Definition TcpMessage.h:97
Contains a data stream which can be sent and received by the Tcp classes.
Definition TcpMessage.h:168
int getActionCode() const
std::size_t getRawMsgSize() const
char * getRawMsgPt()
A special Tcp message, with which the ServerAcceptReceiver can register a new Client.
Definition TcpMessage.h:587
std::map< SOCKET, ServerReceiverTransmitter *, std::less< SOCKET > > m_ClientMap
Definition TcpServer.h:553
Is a special Tcp message for the Server. The socket is included so that the server knows to whom it s...
Definition TcpMessage.h:725

The MyTestServer class can be tried out as follows:

ServerMain.cpp

#ifdef _MSC_VER
#ifdef _DEBUG
// detect Memory-Leaks
#include <crtdbg.h>
#define _CRTDBG_MAP_ALLOC
#endif
#endif
#ifdef _DEBUG_MEMORY_SPY
#include <MliForMain.h>
#endif
#include "MyTestServer.h"
#include <EuException.h>
#include <iostream>
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <conio.h>
#elif defined(__GNUC__)
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
//---------------------------------------------------------------------------
int _getche()
{
char ch = 0;
struct termios tOld;
fflush( stdout );
if ( tcgetattr( 0, & tOld ) < 0 )
{
perror("tcgetattr");
}
tOld.c_lflag &= ~ICANON;
tOld.c_lflag &= ~ECHO;
tOld.c_cc[VMIN] = 1;
tOld.c_cc[VTIME] = 0;
if ( tcsetattr( 0, TCSANOW, & tOld ) < 0 )
{
perror("tcsetattr ICANON");
}
if ( read( 0, & ch, 1 ) < 0 )
{
perror("read");
}
tOld.c_lflag |= ICANON;
tOld.c_lflag |= ECHO;
if ( tcsetattr( 0, TCSADRAIN, & tOld ) < 0 )
{
perror("tcsetattr ~ICANON");
}
return ch;
}
//---------------------------------------------------------------------------
int _kbhit( void )
{
static int ch = 0,
fd = 0;
struct termios tNew,
tOld;
tcgetattr( fd, & tOld );
memcpy( & tNew, & tOld, sizeof( tNew ) );
tNew.c_lflag = tNew.c_lflag & ( ! ICANON );
tNew.c_cc[VMIN] = 0;
tNew.c_cc[VTIME] = 1;
tcsetattr( fd, TCSANOW, & tOld );
if ( ch != -1 ) ungetc( ch, stdin );
return ( ( ch != -1 ) ? 1 : 0 );
}
//---------------------------------------------------------------------------
#endif
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
#ifdef _DEBUG
// Display the memory leaks if any are present...
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
// Next line with the memory address from "{ } ({56} normal block at 0x00D01C78, 10 bytes long.)".
//_crtBreakAlloc = 1149;
#endif
#endif
#ifdef _DEBUG_MEMORY_SPY
MemSpy::activateMemoryMonitoring();
#endif
MyTestServer * t_pServer(0);
int t_iErr = 0;
std::string t_sServerOutput;
char t_Key;
unsigned long t_ulMaxClients = 2;
try
{
// Server starten
t_pServer = new MyTestServer( 12345, PF_INET, SOCK_STREAM, 0, 150, t_ulMaxClients, 5 );
}
catch( eut::ErrorNException ERR )
{
std::cout << "new MyTestServer Err: " << ERR.error() << std::endl;
std::cout << "press key";
t_Key = _getche();
return ERR.error();
}
std::cout << "Server started -> max clients="<< t_ulMaxClients << std::endl;
do
{
std::cout << "Input for all clients or 'q' for exit:" << std::endl;
std::cin >> t_sServerOutput;
t_iErr = t_pServer->sendToAllClients( t_sServerOutput );
} while ( ! t_iErr && t_sServerOutput != "q" );
t_pServer->cancel();
delete t_pServer;
#ifdef _DEBUG_MEMORY_SPY
// Display memory leaks
MemSpy::finishMemoryMonitoring( MemSpy::OUTPUT_TRACE | MemSpy::OUTPUT_CONSOLE );
#endif
std::cout << "press key";
t_Key = _getche();
return t_iErr;
}
Header for ErrorNException
An example class for a simple server derived from Server.
Definition MyTestServer.h:85
This exception class has an integer attribute for an error number in addition to the message.
Definition EuException.h:73
int error() const
Definition EuException.h:276
Author
Helmut Jakoby

Constructor & Destructor Documentation

◆ MyTestServer() [1/5]

MyTestServer::MyTestServer ( )
protected

This constructor is not available.

◆ MyTestServer() [2/5]

MyTestServer::MyTestServer ( unsigned int ,
int ,
int ,
int ,
int  )
protected

This constructor is not available.

◆ MyTestServer() [3/5]

MyTestServer::MyTestServer ( unsigned int ,
int ,
int ,
int ,
unsigned int ,
int  )
protected

This constructor is not available.

◆ MyTestServer() [4/5]

MyTestServer::MyTestServer ( unsigned int uiPort,
int iAdressFamily,
int iSocketType,
int iProtocol,
unsigned int uiDataSize,
unsigned long ulMaxClients,
int iSecTimeOut )

The constructor starts the server.

Parameters
[in]uiPortThe port of the server.
[in]iAdressFamilyThe socket address family to instantiate a socket (usually AF_INET ).
[in]iSocketTypeThe socket type (usually SOCK_STREAM ).
[in]iProtocolThe socket protocol (usually 0).
[in]uiDataSizeThe packet size.
[in]ulMaxClientsThe maximum number of clients allowed to connect.
[in]iSecTimeOutThe time until waiting for a connection or waiting for data is aborted.
Exceptions
eut::ErrorNExceptionAn exception is thrown if an error occurs.

◆ ~MyTestServer()

virtual MyTestServer::~MyTestServer ( )
virtual

Destructor.

◆ MyTestServer() [5/5]

MyTestServer::MyTestServer ( const MyTestServer & )
private

The copy constructor is not available.

Member Function Documentation

◆ insertNewClient()

virtual void MyTestServer::insertNewClient ( Server::ServerReceiverTransmitter * pNewServerReceiverTransmitter)
protectedvirtual

Inserts a new client as 'ServerReceiverTransmitter' in its m_ClientMap. After the same call in the superclass, displays the client here via std::cout.

Parameters
[in]pNewServerReceiverTransmitterThe client is in this object.

◆ operator=()

MyTestServer & MyTestServer::operator= ( const MyTestServer & )
private

The assignment operator is not available.

◆ processClientMessage()

virtual void MyTestServer::processClientMessage ( tcp::AbstractMessage * pTcpMessage)
virtual

Outputs a message from a connected client via std::cout.

Parameters
[in]pTcpMessageThe message to be processed from the server.

Reimplemented from tcp::Server.

◆ sendToAllClients()

int MyTestServer::sendToAllClients ( std::string strMsg)

Sends a text message to all connected clients.

Parameters
[in]strMsgThe message to be sent.
Returns
A return < 0 indicates an error.

The documentation for this class was generated from the following file: