MLIB
Loading...
Searching...
No Matches
mlib::tcpserver Class Reference

multi-threaded TCP server. More...

Inheritance diagram for mlib::tcpserver:
mlib::thread mlib::syncbase mlib::httpd

Public Member Functions

 tcpserver (unsigned short port, const std::string &name=std::string(), unsigned int max_conn=0)
 Opens the socket and initializes the connections table.
 
 ~tcpserver ()
 Terminate any connection that still exists.
 
socksocket ()
 Provides access to server listening socket.
 
void foreach (conn_iter_func f, void *param)
 Invoke an iteration function for each active connection.
 
threadget_connection_thread (const sock &conn_sock)
 Return the thread servicing a connection.
 
void close_connection (const sock &conn_sock)
 Closes a connection.
 
void terminate ()
 Terminate the tcp server.
 
size_t numconn () const
 Return number of active connections.
 
unsigned int timeout () const
 Return max interval to wait for an incoming connection (in milliseconds)
 
void timeout (DWORD msec)
 Set maximum timeout interval (in milliseconds)
 
void maxconn (unsigned int new_max)
 Set maximum number of connections accepted.
 
unsigned int maxconn () const
 Return maximum number of connections accepted.
 
void set_connfunc (std::function< int(const sock &)> f)
 Set function object that becomes the body of the thread serving a new connection.
 
- Public Member Functions inherited from mlib::thread
 thread (std::function< unsigned int()> func)
 Make a thread with the given function body.
 
virtual ~thread ()
 Destructor.
 
virtual void start ()
 Begin execution of a newly created thread.
 
void fork ()
 Another name for start () function.
 
void join ()
 Another name for wait () function.
 
DWORD wait (DWORD time_limit=INFINITE)
 Wait for thread to finish execution.
 
DWORD wait_alertable (DWORD time_limit=INFINITE)
 Wait for thread to finish or an APC, or IO completion routine to occur.
 
DWORD wait_msg (DWORD time_limit=INFINITE, DWORD mask=QS_ALLINPUT)
 Wait for thread to finish or a message to be queued.
 
void rethrow_exception () const
 Rethrow an exception usually in the context of another thread.
 
DWORD id () const
 Return thread's ID.
 
UINT result () const
 Return thread's exit code.
 
bool is_running () const
 Return true if thread is running.
 
state get_state () const
 Return thread's execution status.
 
int priority () const
 Return thread's priority.
 
void priority (int pri)
 Set thread's priority.
 
virtual void name (const std::string &nam)
 Set thread's name.
 
virtual const std::string & name () const
 Return object's name.
 
virtual void name (const std::string &nam)
 Change object's name.
 
- Public Member Functions inherited from mlib::syncbase
 syncbase ()
 Default constructor.
 
 syncbase (const syncbase &e)
 Copy constructor.
 
 syncbase (syncbase &&e) noexcept
 Move constructor.
 
virtual ~syncbase ()
 Destructor.
 
syncbaseoperator= (const syncbase &rhs)
 Assignment operator.
 
syncbaseoperator= (syncbase &&rhs) noexcept
 Move assignment operator.
 
int operator== (const syncbase &rhs) const
 Equality operator.
 
virtual void wait ()
 Wait for object to become signaled.
 
virtual DWORD wait (std::chrono::milliseconds limit)
 Wait a number of milliseconds for the object to become signaled.
 
 operator bool ()
 Check if object is signaled.
 
virtual bool is_signaled ()
 Try to wait on the object.
 
HANDLE handle () const
 Return OS handle of this object.
 

Protected Member Functions

bool init () override
 Binds the server socket to listening address and places it in listen mode.
 
void run () override
 Run loop.
 
virtual bool idle_action ()
 Called periodically from run loop.
 
virtual void initconn (sock &conn_sock, thread *thread)
 Initializes a connection.
 
virtual void termconn (sock &conn_sock, thread *thread)
 Finalizes a connection.
 
virtual threadmake_thread (sock &conn_sock)
 Return a servicing thread for each connection.
 
- Protected Member Functions inherited from mlib::thread
 thread (const std::string &name=std::string(), DWORD stack_size=0, PSECURITY_DESCRIPTOR sd=NULL, bool inherit=false)
 Protected constructor for use of thread-derived objects.
 
virtual void term ()
 Finalization function called after run.
 
- Protected Member Functions inherited from mlib::syncbase
 syncbase (const std::string &name)
 Protected constructor.
 
void set_handle (HANDLE h)
 Change object's handle. Closes the previous one.
 

Additional Inherited Members

- Public Types inherited from mlib::thread
enum class  state {
  ready , starting , running , ending ,
  finished
}
 Execution state of a thread. More...
 
- Protected Attributes inherited from mlib::thread
unsigned int exitcode
 exit code
 

Detailed Description

multi-threaded TCP server.

A tcpserver object is a thread that, when started, listens on a socket and accepts new connections. Typical use is to create a derived class that overrides initconn and termconn functions to provide appropriate actions when a client connects and disconnects.

By default, the server waits indefinitely until a client connects. You can change this behavior by calling the timeout() function to force server's run loop to execute periodically.

Being a thread itself, the tcpserver object has to be started by calling the start() function. The listening port must be set before the server thread is started. It can be set either when the object is constructed or by calling the bind() function on the listening socket.

The following two examples are equivalent:

Example 1:

mlib::tcpserver srv (12345);
//...
srv.start ();
multi-threaded TCP server.
Definition tcpserver.h:22

Example 2:

srv.socket().bind (mlib::inaddr (INADDR_ANY, 12345));
//...
srv.start ();
sockaddr wrapper
Definition inaddr.h:23
erc bind(const inaddr &) const
Associates a local address with the socket.
Definition wsockstream.cpp:265
sock & socket()
Provides access to server listening socket.
Definition tcpserver.h:85
virtual void start()
Begin execution of a newly created thread.
Definition thread.cpp:168

When a new connection is received (listen() function returns a new socket) the server calls make_thread() to create a new thread servicing the connection. It then starts this new thread by calling initconn().

Constructor & Destructor Documentation

◆ tcpserver()

mlib::tcpserver::tcpserver ( unsigned short  port,
const std::string &  name = std::string (),
unsigned int  max_conn = 0 
)

Opens the socket and initializes the connections table.

Parameters
portlistening port number
nameserver name used for debug messages
max_connmaximum number of accepted connections

If port address is 0, the listening address is the local loop-back interface. Otherwise, the listening address defaults to 'all interfaces' (INADDR_ANY).

Member Function Documentation

◆ close_connection()

void mlib::tcpserver::close_connection ( const sock conn_sock)

Closes a connection.

Parameters
conn_socksocket associated with connection to be closed

The connection is also removed from the connections table. In fact, the connection is only marked as condemned and the run loop will remove it next time it is run.

◆ foreach()

void mlib::tcpserver::foreach ( conn_iter_func  f,
void *  param 
)

Invoke an iteration function for each active connection.

Parameters
ffunction to call
paramarbitrary value passed as second parameter to iteration function

◆ get_connection_thread()

thread * mlib::tcpserver::get_connection_thread ( const sock conn_sock)

Return the thread servicing a connection.

Parameters
conn_socksocket associated with the connection
Returns
pointer to connection servicing thread or NULL of there is no associated thread

◆ idle_action()

bool mlib::tcpserver::idle_action ( )
inlineprotectedvirtual

Called periodically from run loop.

If it returns false the run loop terminates and all connections are closed.

◆ init()

bool mlib::tcpserver::init ( )
overrideprotectedvirtual

Binds the server socket to listening address and places it in listen mode.

Also initializes an event flag to be signaled when a connection request is received. This function is automatically invoked by start ()

Reimplemented from mlib::thread.

◆ initconn()

void mlib::tcpserver::initconn ( sock conn_sock,
thread th 
)
protectedvirtual

Initializes a connection.

Parameters
conn_sockconnection socket
ththread that services the new connection

If the connection has associated a servicing thread (th is not NULL), this thread is started now.

◆ make_thread()

thread * mlib::tcpserver::make_thread ( sock conn_sock)
protectedvirtual

Return a servicing thread for each connection.

Parameters
conn_socksocket associated with the new connection

If user has set a connection function (using set_connfunc() function), the function returns a thread whose body is the connection function. Otherwise, it returns NULL and the server becomes a single-threaded server.

Note
The returned thread should not be started. It will be started from the initconn() function.

Reimplemented in mlib::httpd.

◆ maxconn()

void mlib::tcpserver::maxconn ( unsigned int  n)

Set maximum number of connections accepted.

Set max number of accepted connections.

Parameters
nmaximum number of concurrent connections

◆ run()

void mlib::tcpserver::run ( )
overrideprotectedvirtual

Run loop.

Waits for incoming connections. Every time a connection request is received the following actions take place:

  • check if server can accept more connections

Reimplemented from mlib::thread.

◆ termconn()

void mlib::tcpserver::termconn ( sock conn_sock,
thread th 
)
protectedvirtual

Finalizes a connection.

Parameters
conn_socksocket associated with the connection
thconnection servicing thread

Wait for the servicing thread to terminate (if there is one) than close the socket

◆ timeout() [1/2]

unsigned int mlib::tcpserver::timeout ( ) const
inline

Return max interval to wait for an incoming connection (in milliseconds)

Returns
timeout value in milliseconds

If timeout interval is 0 or INFINITE the server waits indefinitely for incoming connections.

◆ timeout() [2/2]

void mlib::tcpserver::timeout ( DWORD  msec)
inline

Set maximum timeout interval (in milliseconds)

Parameters
msectimeout interval in milliseconds.

If timeout interval is 0 or INFINITE the server waits indefinitely for incoming connections.


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