TEC
A lightweight C++ library enabling safe, efficient execution in multithreaded and concurrent systems.
Loading...
Searching...
No Matches
tec::SocketServer< TParams > Class Template Reference

Generic BSD socket server template using actor pattern with configurable parameters. More...

#include <tec_socket_server.hpp>

Inheritance diagram for tec::SocketServer< TParams >:
tec::Actor tec::SocketServerNd< TParams >

Public Types

using Params = TParams
 Parameter type — must inherit from tec::SocketServerParams
 

Public Member Functions

 SocketServer (const Params &params)
 Constructs server instance with given parameters.
 
virtual ~SocketServer ()=default
 Virtual destructor (default implementation)
 
void start (Signal *sig_started, Status *status) override
 Starts the server: bind → listen → accept loop.
 
void shutdown (Signal *sig_stopped) override
 Gracefully shuts down the server.
 
Status process_request (Request request, Reply reply) override
 Default request processor (not used in socket server)
 
- Public Member Functions inherited from tec::Actor
 Actor ()=default
 Default constructor.
 
 Actor (const Actor &)=delete
 Deleted copy constructor.
 
 Actor (Actor &&)=delete
 Deleted move constructor.
 
Actoroperator= (const Actor &)=delete
 Deleted copy assignment operator.
 
Actoroperator= (Actor &&)=delete
 Deleted move assignment operator.
 
virtual ~Actor ()=default
 Virtual destructor.
 
virtual Status run ()
 Mimics Daemon's behavior.
 
virtual Status terminate ()
 Mimics Daemon's behavior.
 

Protected Member Functions

constexpr charget_buffer ()
 
constexpr size_t get_buffer_size () const
 
virtual Status set_socket_options (int fd)
 Sets common socket options (SO_REUSEADDR, SO_REUSEPORT)
 
virtual Socket get_socket_info (int client_fd, sockaddr_storage *client_addr)
 Creates Socket object from raw file descriptor and peer address.
 
virtual Status resolve_and_bind_host ()
 Resolves address/port and binds listening socket.
 
virtual Status start_listening ()
 Starts listening on the bound socket.
 
virtual Status accept_connection (int *clientfd, sockaddr_storage *client_addr)
 Accepts one incoming connection (blocking)
 
virtual void poll (Signal *sig_started)
 Main acceptor loop — runs until stop_polling_ is set.
 
virtual void process_socket (Socket sock)
 Decides how to handle newly accepted client socket.
 
virtual void dispatch_socket (Socket _sock)
 Executes client connection handling logic.
 
virtual void close_client_connection (Socket *sock)
 Closes client connection cleanly.
 
virtual void on_string (const Socket *sock)
 Default handler for character-stream / line-based protocols.
 
virtual void on_net_data (const Socket *sock)
 Default handler for binary / structured network protocols.
 

Protected Attributes

Params params_
 Server configuration parameters (address, port, buffer size, threading mode, etc.)
 
int listenfd_
 Listening socket file descriptor (-1 when not bound/listening)
 
std::atomic_bool stop_polling_
 Atomic flag used to signal the acceptor/polling loop to exit.
 
Signal polling_stopped_
 Signal object set when polling loop has fully exited.
 

Detailed Description

template<typename TParams>
class tec::SocketServer< TParams >

Generic BSD socket server template using actor pattern with configurable parameters.

Supports both single-threaded (synchronous) and multi-threaded (thread-pool) modes. Implements the kModeCharStream mode – text oriented (default echo server behavior).

Main responsibilities:

  • address resolution & binding
  • listening
  • accepting connections in a loop
  • dispatching client sockets either synchronously or via thread pool
  • graceful shutdown with proper socket closure
Template Parameters
TParamsMust derive from SocketServerParams
Example
#include <csignal>
#include <sys/socket.h>
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Simplest BSD socket server
* in the kModeCharStream mode (default, receives and sends strings)
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// Instantiate core blocks.
using TCPParams = tec::SocketServerParams;
using TCPServer = tec::SocketServer<TCPParams>;
tec::Signal sig_quit;
tec::Status tcp_server() {
// Accepts both IPv4 and IPv6.
params.family = AF_INET6;
// To accept IPv4 only:
// params.addr = tec::SocketParams::kAnyAddr;
// params.family = AF_INET;
//
// Use internal thread pool to process incoming connections.
// `false` by default.
params.use_thread_pool = true;
// Create TCP server as Daemon.
auto srv{TCPServerWorker::Builder<TCPServerWorker, TCPServer>{}(params)};
// Run it and check for the result.
auto status = srv->run();
if( !status ) {
tec::println("run(): {}", status);
return status;
}
// Wait for <Ctrl-C> pressed to terminate the server.
tec::println("\nPRESS <Ctrl-C> TO QUIT THE SERVER");
sig_quit.wait();
// Terminate the server
status = srv->terminate();
return status;
}
int main() {
// Install Ctrl-C handler.
std::signal(SIGINT, [](int){ sig_quit.set(); });
// Run the server.
auto result = tcp_server();
tec::println("\nExited with {}", result);
return result.code.value_or(0);
}
A Worker that owns and runs an Actor in a dedicated thread.
Definition tec_actor_worker.hpp:76
A thread-safe signal mechanism for inter-thread synchronization.
Definition tec_signal.hpp:44
void set()
Sets the signal to the signaled state and notifies all waiting threads.
Definition tec_signal.hpp:72
void wait() const
Waits indefinitely until the signal is set.
Definition tec_signal.hpp:85
Generic BSD socket server template using actor pattern with configurable parameters.
Definition tec_socket_server.hpp:82
int family
Address family (AF_INET, AF_INET6, AF_UNSPEC, ...).
Definition tec_socket.hpp:105
std::string addr
Target address or hostname.
Definition tec_socket.hpp:102
static constexpr char kAnyAddrIP6[]
IPv6 address to bind/accept connections from any interface.
Definition tec_socket.hpp:72
Parameters specific to server-side socket configuration.
Definition tec_socket.hpp:170
bool use_thread_pool
Use the thread pool for handling accepted connections.
Definition tec_socket.hpp:205
Template class combining Worker and Actor for synchronous request processing in a dedicated thread.
Provides variadic print and format utilities for the tec namespace. Implemented for compatibility wit...
void println(std::ostream *out, const T &arg)
Outputs a single argument to the specified stream with a newline.
Definition tec_print.hpp:90
Generic BSD socket server template using actor pattern with configurable parameters.

Constructor & Destructor Documentation

◆ SocketServer()

template<typename TParams >
tec::SocketServer< TParams >::SocketServer ( const Params params)
inlineexplicit

Constructs server instance with given parameters.

Parameters
paramsConfiguration (address, port, buffer size, threading mode, socket options…)

Does not start listening — call start() to begin serving.

Member Function Documentation

◆ accept_connection()

template<typename TParams >
virtual Status tec::SocketServer< TParams >::accept_connection ( int clientfd,
sockaddr_storage client_addr 
)
inlineprotectedvirtual

Accepts one incoming connection (blocking)

Parameters
[out]clientfdAccepted client file descriptor
[out]client_addrFilled peer address structure
Returns
Status — success or accept() failure/interruption

◆ close_client_connection()

template<typename TParams >
virtual void tec::SocketServer< TParams >::close_client_connection ( Socket sock)
inlineprotectedvirtual

Closes client connection cleanly.

Parameters
sockSocket to close (fd set to -1 after close)

◆ dispatch_socket()

template<typename TParams >
virtual void tec::SocketServer< TParams >::dispatch_socket ( Socket  _sock)
inlineprotectedvirtual

Executes client connection handling logic.

Parameters
_sockClient socket (moved or copied)

Dispatches to mode-specific handler (on_string or on_net_data). Always closes connection when handler returns.

◆ get_buffer()

template<typename TParams >
constexpr char * tec::SocketServer< TParams >::get_buffer ( )
inlineconstexprprotected
Returns
Pointer to the per-connection buffer (single-threaded mode only)

◆ get_buffer_size()

template<typename TParams >
constexpr size_t tec::SocketServer< TParams >::get_buffer_size ( ) const
inlineconstexprprotected
Returns
Configured buffer size for client connections

◆ get_socket_info()

template<typename TParams >
virtual Socket tec::SocketServer< TParams >::get_socket_info ( int  client_fd,
sockaddr_storage client_addr 
)
inlineprotectedvirtual

Creates Socket object from raw file descriptor and peer address.

Parameters
client_fdAccepted client socket fd
client_addrPeer address structure (IPv4 or IPv6)
Returns
Filled Socket structure with IP, port and buffer info
Note
Socket::port == -1 indicates address or port detection failure.
Override this method in a derived class to enable other protocols.

◆ on_net_data()

template<typename TParams >
virtual void tec::SocketServer< TParams >::on_net_data ( const Socket sock)
inlineprotectedvirtual

Default handler for binary / structured network protocols.

Parameters
sockClient connection

Empty by default — override in derived classes.

Reimplemented in tec::SocketServerNd< TParams >.

◆ on_string()

template<typename TParams >
virtual void tec::SocketServer< TParams >::on_string ( const Socket sock)
inlineprotectedvirtual

Default handler for character-stream / line-based protocols.

Parameters
sockClient connection

Default implementation: simple echo server. Override in derived classes for real protocol handling.

◆ poll()

template<typename TParams >
virtual void tec::SocketServer< TParams >::poll ( Signal sig_started)
inlineprotectedvirtual

Main acceptor loop — runs until stop_polling_ is set.

Parameters
sig_startedSignal to set once loop has started

◆ process_request()

template<typename TParams >
Status tec::SocketServer< TParams >::process_request ( Request  request,
Reply  reply 
)
inlineoverridevirtual

Default request processor (not used in socket server)

Returns
Always returns NotImplemented

Implements tec::Actor.

◆ process_socket()

template<typename TParams >
virtual void tec::SocketServer< TParams >::process_socket ( Socket  sock)
inlineprotectedvirtual

Decides how to handle newly accepted client socket.

Parameters
sockFilled client socket information

Routes to thread pool (async) or direct dispatch (sync) based on configuration.

◆ resolve_and_bind_host()

template<typename TParams >
virtual Status tec::SocketServer< TParams >::resolve_and_bind_host ( )
inlineprotectedvirtual

Resolves address/port and binds listening socket.

Returns
Status — success or detailed bind failure reason

◆ set_socket_options()

template<typename TParams >
virtual Status tec::SocketServer< TParams >::set_socket_options ( int  fd)
inlineprotectedvirtual

Sets common socket options (SO_REUSEADDR, SO_REUSEPORT)

Parameters
fdSocket file descriptor to configure
Returns
Status indicating success or specific socket error. Default implementation always returns OK.

◆ shutdown()

template<typename TParams >
void tec::SocketServer< TParams >::shutdown ( Signal sig_stopped)
inlineoverridevirtual

Gracefully shuts down the server.

Parameters
sig_stoppedSignal to set when shutdown is complete

Closes listening socket and waits until acceptor loop exits. Running client handlers (in thread pool) are allowed to finish.

Implements tec::Actor.

◆ start()

template<typename TParams >
void tec::SocketServer< TParams >::start ( Signal sig_started,
Status status 
)
inlineoverridevirtual

Starts the server: bind → listen → accept loop.

Parameters
sig_startedSignal to set once server is ready (bound & listening)
status[out] Result of initialization (binding/listening)

Called from actor framework. Blocking until server is stopped.

Implements tec::Actor.

◆ start_listening()

template<typename TParams >
virtual Status tec::SocketServer< TParams >::start_listening ( )
inlineprotectedvirtual

Starts listening on the bound socket.

Returns
Status — success or listen() failure

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