TcpLib
Loading...
Searching...
No Matches
tcp::Server Class Reference

A simple TCP server class, which should learn its know-how in the derived classes. More...

#include <TcpServer.h>

Inheritance diagram for tcp::Server:
Collaboration diagram for tcp::Server:

Classes

class  ServerReceiverTransmitter
 Tuple of socket Receiver and Transmitter for the Server. More...
 

Public Member Functions

 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

 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 void processClientMessage (AbstractMessage *pTcpMessage)
 
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 ()
 

Protected Attributes

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
 

Private Member Functions

 Server (const Server &rT)
 
void init ()
 
Serveroperator= (const Server &)
 

Private Attributes

unsigned long m_ulMaxClients
 
std::queue< AbstractMessage * > m_MsgQueue
 

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 }
 

Detailed Description

A simple TCP server class, which should learn its know-how in the derived classes.

Server is a thread that allows Tcp Client's to connect to it.

TcpServers have as superclass attributes the port, the data size which is sent, the address family, the socket type, the protocol type and a main socket (here AcceptSocket).

In addition, the following attributes are available here: a ServerAcceptReceiver, which processes the new requests as a thread, a MsgQueue, which records the individual messages of the individual ClientSockets, a counter that contains the maximum number of clients and a ClientMap with the individual ServerReceiverTransmitter objects.

For each accepted client, an object of the embedded class ServerReceiverTransmitter is instantiated, which has a Transmitter and a Receiver, and stored in the ClientMap. Transmitter and Receiver are also threads.

Starting the server:

During instantiation with transfer of port, address family, socket type, protocol, data size and maximum number of clients, the own thread and the ServerAcceptReceiver is initialized (with the calling server as parent object and the main socket) and also started as a thread. This always blocks until a client logs on.

New client wants to connect:

When a client logs on to the ServerAcceptReceiver, a new ServerAcceptMessage instantiated (with the new SOCKET of the client as parameter) and to the server via Server::acceptClientMessage(AbstractMessage *) passed on.

In Server::acceptClientMessage(AbstractMessage *) the passed ServerAcceptMessage is appended to the MsgQueue. When the MsgQueue is processed in Server::work(), the ServerAcceptMessage is found.

If the maximum number of clients is exceeded, the client is informed and the client socket is closed.

If the client socket is not closed, a ServerReceiverTransmitter is instantiated using a virtual method Server::generateNewServerReceiverTransmitter (...). The server is passed as the parent object for the ServerReceiver that is still to be instantiated, the new socket and the data size. A Transmitter (which sends data to the new client) and a ServerReceiver (which receives data from the new client) are instantiated for the ServerReceiverTransmitter. It is possible to establish a derived ServerReceiverTransmitter with derived Transmitter or ServerReceiver.

The new ServerReceiverTransmitter is inserted into the ClientMap.

Now the server method Server::processClientMessage(AbstractMessage *) is called, in which further processing can be carried out in subclasses. Among other things, the ServerAcceptMessage is removed from the memory.

The new ServerReceiverTransmitter or its ServerReceiver in the ClientMap is now responsible for further messages from the client.

Processing data from the client:

The ServerReceiver waits in its thread method ServerReceiver::work() for messages from the connected client. If the client sends (abort or data), the ServerReceiver creates a new ServerMessage using the method ServerReceiver::generateNewTcpMessage (... ) (can be overwritten in subclasses to return derived message types) and forwarded to the parent server Server::acceptClientMessage(AbstractMessage *) using the method ServerReceiver::acceptMessage(AbstractMessage *).

In subclasses, a derived ServerReceiver can take over processing in the overwritten ServerReceiver::acceptMessage(AbstractMessage *) and/or the derived Server can take over processing in the overwritten Server::acceptClientMessage(AbstractMessage *).

In the method Server::acceptClientMessage(AbstractMessage *), the transferred ServerMessage is appended to the MsgQueue. When the MsgQueue is processed, the ServerMessage is found and forwarded to Server::processClientMessage(AbstractMessage *). If the client has broken the connection, the message is modified and the client is removed using Server::removeClient(SOCKET Socket)).

In Server::processClientMessage(AbstractMessage *), as mentioned above, special processing can be performed in subclasses; only the ServerAcceptMessage is removed from memory here.

Sending to the client:

Must be worked out in subclasses of Server or subclasses of ServerReceiverTransmitter or otherwise. At least all classes have access to the socket.

Exit from Server:

First the server thread is stopped, then the ServerAcceptReceiver is removed from memory. Finally, all TcpServerReceivers are removed from the ClientMap and memory.

Author
Helmut Jakoby

Constructor & Destructor Documentation

◆ Server() [1/5]

tcp::Server::Server ( )
protected

This constructor is not available.

◆ Server() [2/5]

tcp::Server::Server ( unsigned int ,
int ,
int ,
int ,
int  )
protected

This constructor is not available.

◆ Server() [3/5]

tcp::Server::Server ( unsigned int ,
int ,
int ,
int ,
unsigned int ,
int  )
protected

This constructor is not available.

◆ Server() [4/5]

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

This 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.

◆ ~Server()

virtual tcp::Server::~Server ( )
virtual

Destructor. It is cleaned up (AcceptReceiver and MsgQueue).

◆ Server() [5/5]

tcp::Server::Server ( const Server & rT)
private

The copy constructor is not available.

Member Function Documentation

◆ acceptClientMessage()

int tcp::Server::acceptClientMessage ( AbstractMessage * pTcpMessage)

The transferred Message is inserted into the MsgQueue by the client via the ServerAcceptReceiver or ServerReceiver and is thus processed.

Parameters
[in]pTcpMessageThe received message from the client.
Returns
A return < 0 indicates an error.

◆ cancel()

virtual void tcp::Server::cancel ( )
overridevirtual

When the thread ends, this virtual method is called. The MsgQueue is cleaned up here.

Note
This method only exists when not compiled with POSIX threads (defined (__PTHREADS)).

Reimplemented from eut::RepeatingThread.

◆ clearClientMap()

void tcp::Server::clearClientMap ( )
protected

Removes all ServerReceiverTransmitters from its list of clients and from memory.

◆ generateNewServerReceiverTransmitter()

virtual Server::ServerReceiverTransmitter * tcp::Server::generateNewServerReceiverTransmitter ( Server * pParent,
SOCKET Socket,
unsigned int iDataSize ) const
protectedvirtual

Returns a ServerReceiverTransmitter here; can be overwritten in subclasses to return a derived type. Is called in work() when a new client is added.

Parameters
[in]pParentServer or subclass.
[in]SocketSocket of the new client.
[in]iDataSizeThe packet size.
Returns
The ServerReceiverTransmitter or derived type required in the subclasses.

◆ getClient()

Server::ServerReceiverTransmitter * tcp::Server::getClient ( SOCKET Socket)
protected

Looks for the ServerReceiverTransmitter corresponding to the 'Socket' parameter in its list of clients and returns a pointer to it, if any.

Parameters
[in]SocketThe socket of the ServerReceiverTransmitter being searched for.
Returns
If != 0, then the ServerReceiverTransmitter found.
Attention
The returned object only lives as long as the returning object and must NOT be removed from memory by the calling instance.

◆ getMaxClients()

unsigned long tcp::Server::getMaxClients ( ) const
protected

Returns the maximum number of client connections allowed.

Returns
The maximum number of client connections allowed.

◆ init()

void tcp::Server::init ( )
private

Initializes the socket and instantiates a ServerAcceptReceiver. The own attributes must have meaningful values.

Exceptions
eut::ErrorNExceptionAn exception is thrown if an error occurs.

◆ insertNewClient()

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

Adds new client as 'ServerReceiverTransmitter' to its list of clients. This method is virtual, so that subclasses can react to it; e.g. let someone know that a new client has arrived.

Parameters
[in]pNewServerReceiverTransmitterThe client is in this object.

◆ operator=()

Server & tcp::Server::operator= ( const Server & )
private

The assignment operator is not available.

◆ processClientMessage()

virtual void tcp::Server::processClientMessage ( AbstractMessage * pTcpMessage)
protectedvirtual

Should process the message from the client in subclasses. In the overwritten methods always this method must be called, because among other things the passed Message is removed from the memory here.

Parameters
[in]pTcpMessageThe message to be processed by the client.

Reimplemented in MyTestServer.

◆ removeClient()

virtual int tcp::Server::removeClient ( SOCKET Socket)
protectedvirtual

Looks for the ServerReceiverTransmitter corresponding to the 'Socket' parameter in its list of clients and removes it from the list and from memory.

Parameters
[in]SocketThe socket to be closed.
Returns
A return value < 0 indicates an error.

◆ send() [1/2]

virtual int tcp::Server::send ( Message * pTcpMessage)
overrideprotectedvirtual

Sends the transferred Message to the client via its Transmitter (Client information is in the ServerMessage).

Parameters
[in]pTcpMessageThe message packet to be sent must be a ServerMessage.
Returns
A return < 0 indicates an error.
Attention
The passed Message must not be removed from memory by the calling instance! Since the Message is given to the Transmitter for further processing, and the Transmitter decides when to send. Therefore, the Transmitter will also remove the Message from memory.

Implements tcp::TcpMain.

◆ send() [2/2]

virtual int tcp::Server::send ( SOCKET ClientSocket,
char * pszRawMsg,
unsigned int uiRawMsgSize,
unsigned int uiMessageID = 0,
int iActionCode = 0,
const std::string & rstrInfo = "" )
protectedvirtual

Sends the transferred data in a Message via its Transmitter to the client. A header will be generated.

Parameters
[in]ClientSocketThe socket of the target client.
[in]pszRawMsgPointer to the data to be sent.
[in]uiRawMsgSizeThe size of the data to be sent.
[in]uiMessageIDA MessageID can be passed.
[in]iActionCodeA ActionCode can be passed.
[in]rstrInfoA free info can be passed.
Returns
A return value < 0 indicates an error.
Attention
The data in pszRawMsg is internally removed from memory; the calling instance may no longer use the data to be sent or remove it from memory.

◆ setClientMapReceiverValid()

void tcp::Server::setClientMapReceiverValid ( bool bValid)
protected

Sets the Valid flag for all ServerReceiverTransmitters from its list of clients.

Parameters
[in]bValidIf false -> no more reception!

◆ work()

virtual void tcp::Server::work ( )
overrideprotectedvirtual

Work of the thread. New clients will be 'accepted' or rejected when the maximum number is reached. Messages from clients are processed.

Implements eut::RepeatingThread.

Member Data Documentation

◆ m_ClientMap

std::map< SOCKET, ServerReceiverTransmitter *, std::less< SOCKET > > tcp::Server::m_ClientMap
protected

All accepted clients in Server::ServerReceiverTransmitter.

◆ m_MsgQueue

std::queue<AbstractMessage *> tcp::Server::m_MsgQueue
private

The queue with the received data from the client.

◆ m_pAcceptReceiver

ServerAcceptReceiver* tcp::Server::m_pAcceptReceiver
protected

The AcceptReceiver accepts new clients.

◆ m_ulMaxClients

unsigned long tcp::Server::m_ulMaxClients
private

The maximum number of clients to accept. If the number is exceeded, no more clients are accepted.


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