STTNet
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
Public Member Functions | Protected Attributes | List of all members
stt::network::TcpServer Class Referenceabstract

Tcp server class. More...

#include <sttnet_English.h>

Inheritance diagram for stt::network::TcpServer:
stt::network::HttpServer stt::network::WebSocketServer

Public Member Functions

void putTask (const std::function< int(TcpFDHandler &k, TcpInformation &inf)> &fun, TcpFDHandler &k, TcpInformation &inf)
 Add a task to a worker thread pool and have it completed by worker threads. More...
 
 TcpServer (const unsigned long long &maxFD=1000000, const int &buffer_size=256, const bool &security_open=true, const int &connectionNumLimit=20, const int &connectionSecs=1, const int &connectionTimes=6, const int &requestSecs=1, const int &requestTimes=40, const int &checkFrequency=60, const int &connectionTimeout=60)
 Constructor. More...
 
bool startListen (const int &port, const int &threads=8)
 Start the TCP server listening program. More...
 
bool setTLS (const char *cert, const char *key, const char *passwd, const char *ca)
 Enable TLS encryption and configure server-side certificate and key. More...
 
void redrawTLS ()
 Revoke TLS encryption, CA certificate, etc. More...
 
void setSecuritySendBackFun (std::function< void(TcpFDHandler &k, TcpInformation &inf)> fc)
 Set the callback invoked when an information security policy is violated. More...
 
void setGlobalSolveFunction (std::function< bool(TcpFDHandler &k, TcpInformation &inf)> fc)
 Set global fallback function. More...
 
void setFunction (const std::string &key, std::function< int(TcpFDHandler &k, TcpInformation &inf)> fc)
 Register a callback function for a specific key. More...
 
void setGetKeyFunction (std::function< int(TcpFDHandler &k, TcpInformation &inf)> parseKeyFun)
 Set the callback function used to parse the key. More...
 
bool stopListen ()
 Stop listening. More...
 
bool close ()
 Close listening and all connected sockets. More...
 
virtual bool close (const int &fd)
 Close the connection of a specific socket. More...
 
void setCloseFun (std::function< void(const int &fd)> closeFun)
 set function after tcp connection close More...
 
bool isListen ()
 Return the listening status of the object. More...
 
SSL * getSSL (const int &fd)
 Query the connection with the server, pass in the socket, and return the encrypted SSL handle. More...
 
 ~TcpServer ()
 Destructor of TcpServer class. More...
 

Protected Attributes

std::queue< WorkerMessagefinishQueue
 
stt::system::WorkerPoolworkpool
 
unsigned long buffer_size
 
unsigned long long maxFD
 
security::ConnectionLimiter connectionLimiter
 
TcpFDInfclientfd
 
int flag1 =true
 
bool unblock
 
SSL_CTX * ctx =nullptr
 
bool TLS =false
 
bool security_open
 
int workerEventFD
 
int serverType
 
int connectionSecs
 
int connectionTimes
 
int requestSecs
 
int requestTimes
 
int checkFrequency
 

Detailed Description

Tcp server class.

Note
The default underlying implementation is epoll edge trigger + socket non-blocking mode

Constructor & Destructor Documentation

stt::network::TcpServer::TcpServer ( const unsigned long long &  maxFD = 1000000,
const int &  buffer_size = 256,
const bool &  security_open = true,
const int &  connectionNumLimit = 20,
const int &  connectionSecs = 1,
const int &  connectionTimes = 6,
const int &  requestSecs = 1,
const int &  requestTimes = 40,
const int &  checkFrequency = 60,
const int &  connectionTimeout = 60 
)
inline

Constructor.

By default, allows up to 1,000,000 concurrent connections, allocates a maximum receive buffer of 256 KB per connection, and enables the security module.

Note
Enabling the security module will introduce additional overhead and may impact performance.
Parameters
maxFDMaximum number of connections this server instance can accept. Default: 1,000,000.
buffer_sizeMaximum amount of data a single connection is allowed to receive, in kilobytes (KB). Default: 256 KB.
security_openWhether to enable the security module.
  • true : enable security checks (default)
  • false : disable security checks
connectionNumLimitMaximum number of concurrent connections allowed per IP. Default: 20.
connectionSecsTime window (in seconds) for connection rate limiting. Default: 1 second.
connectionTimesMaximum number of connection attempts allowed within connectionSecs seconds. Default: 6.
requestSecsTime window (in seconds) for request rate limiting. Default: 1 second.
requestTimesMaximum number of requests allowed within requestSecs seconds. Default: 40.
checkFrequencyFrequency (in seconds) for checking zombie/idle connections. -1 disables zombie connection detection. Default: 60 seconds.
connectionTimeoutIf a connection has no activity for this many seconds, it is considered a zombie connection. -1 means no timeout (infinite). Default: 60 seconds.
stt::network::TcpServer::~TcpServer ( )
inline

Destructor of TcpServer class.

Note
Calls the close function to close

Member Function Documentation

bool stt::network::TcpServer::close ( )

Close listening and all connected sockets.

Note
Closes listening and all connected sockets, registered callback functions and TLS will not be deleted or redrawn
Will block until all closures are complete
Returns
true: Closed successfully, false: Failed to close
virtual bool stt::network::TcpServer::close ( const int &  fd)
virtual

Close the connection of a specific socket.

Parameters
fdSocket to be closed
Returns
true: Closed successfully, false: Failed to close

Reimplemented in stt::network::WebSocketServer.

SSL* stt::network::TcpServer::getSSL ( const int &  fd)

Query the connection with the server, pass in the socket, and return the encrypted SSL handle.

Returns
Encrypted SSL pointer; returns nullptr if this fd does not exist or there is no encryption
bool stt::network::TcpServer::isListen ( )
inline

Return the listening status of the object.

Returns
true: Listening, false: Not listening
void stt::network::TcpServer::putTask ( const std::function< int(TcpFDHandler &k, TcpInformation &inf)> &  fun,
TcpFDHandler k,
TcpInformation inf 
)

Add a task to a worker thread pool and have it completed by worker threads.

Note
Slow, blocking I/O tasks should be placed in a worker thread pool.
Warning
Executable objects must return values ​​strictly according to the specified return values.
Parameters
funExecutable objects placed in the worker thread pool -parameter:TcpFDHandler &k - References to the operation objects of the socket connected to the client TcpFDInf &inf - Client information, saved data, processing progress, state machine information, etc. -return value:-2:Processing failed and connection needs to be closed -1: Processing failed but connection does not need to be closed 1: Processing succeeded
kReferences to the operation objects of the socket connected to the client
infReferences to client information, data storage, processing progress, state machine information, etc.
void stt::network::TcpServer::redrawTLS ( )

Revoke TLS encryption, CA certificate, etc.

void stt::network::TcpServer::setCloseFun ( std::function< void(const int &fd)>  closeFun)
inline

set function after tcp connection close

void stt::network::TcpServer::setFunction ( const std::string &  key,
std::function< int(TcpFDHandler &k, TcpInformation &inf)>  fc 
)
inline

Register a callback function for a specific key.

Note
Multiple callbacks can be registered for the same key. The framework will execute them sequentially in the order they are registered. You may also choose to dispatch the processing to a worker thread pool by returning specific values.
Warning
The callable object must strictly follow the required return value conventions.
Parameters
keyThe key used to locate the corresponding callback function.
fcA function or function object that defines the logic to handle incoming client messages.
  • Parameters: TcpFDHandler &k - Reference to the socket operation object associated with the client connection. TcpInformation &inf - Client information, including received data, processing progress, state machine data, etc.
  • Return value: -2 : Processing failed and the connection must be closed. -1 : Processing failed but the connection should remain open. 0 : Processing has been dispatched to a worker thread pool and the framework should wait for completion. 1 : Processing succeeded.
void stt::network::TcpServer::setGetKeyFunction ( std::function< int(TcpFDHandler &k, TcpInformation &inf)>  parseKeyFun)
inline

Set the callback function used to parse the key.

Note
This function extracts the key from the input parameters and stores it in the ctx hash table within TcpInformation. The framework uses this key to locate the registered processing callbacks.
Warning
The callable object must strictly follow the required return value conventions.
Parameters
parseKeyFunThe callback function used to parse the key.
  • Parameters: TcpFDHandler &k - Reference to the socket operation object associated with the client connection. TcpInformation &inf - Client information, including received data, processing progress, state machine data, etc.
  • Return value: -2 : Processing failed and the connection must be closed. -1 : Processing failed but the connection should remain open. 0 : Processing has been dispatched to a worker thread pool and the framework should wait for completion. 1 : Processing succeeded.
void stt::network::TcpServer::setGlobalSolveFunction ( std::function< bool(TcpFDHandler &k, TcpInformation &inf)>  fc)
inline

Set global fallback function.

Note
When a corresponding callback function cannot be found, a global backup function will be called.
Parameters
keyFind the key of the corresponding callback function
fcA function or function object used for processing logic after receiving a message from the client. -Parameters: TcpFDHandler &k - A reference to the operation object of the socket connected to the client. TcpInformation &inf - Client information, saved data, processing progress, state machine information, etc. -Return value: true: Processing successful; false: Processing failed and the connection will be closed.
void stt::network::TcpServer::setSecuritySendBackFun ( std::function< void(TcpFDHandler &k, TcpInformation &inf)>  fc)
inline

Set the callback invoked when an information security policy is violated.

This callback is executed when a TCP client violates a security rule (e.g. connection abuse, rate limiting, malformed data, or other security-related conditions). After the callback is executed, the connection will be closed.

Note
The callback is invoked once per security violation. The connection is closed unconditionally after the callback returns.
Parameters
fcA function or function object used to handle the response sent back to the client upon a security violation.

Callback parameters:

  • TcpFDHandler &k Reference to the handler object used to operate on the client socket/connection.
  • TcpInformation &inf Client-related information, including buffered data, processing progress, and protocol/state-machine context.
Note
The callback does not return a value. The connection will be closed regardless of the callback outcome.
bool stt::network::TcpServer::setTLS ( const char *  cert,
const char *  key,
const char *  passwd,
const char *  ca 
)

Enable TLS encryption and configure server-side certificate and key.

This function initializes OpenSSL and enables TLS (SSL/TLSv1 protocol family) support for the TCP server. It loads the server-side certificate, private key, and an optional CA root certificate for peer verification.

If TLS is already enabled, the context will be automatically rebuilt (reloaded).

Parameters
certServer certificate chain file path (usually PEM format, including intermediate certificates)
keyPrivate key file path (matching PEM format key for the certificate)
passwdPassword for the private key file (can be an empty string if the key is not encrypted)
caCA root certificate path for verifying client certificates (PEM format)
Note
The protocol method used is SSLv23_method(), which actually supports SSLv3/TLSv1/TLSv1.1/TLSv1.2 and higher versions (depending on the OpenSSL version and configuration)
The certificate verification policy uses SSL_VERIFY_FAIL_IF_NO_PEER_CERT, meaning:
  • If the client does not provide a certificate, the handshake fails (safer, recommended)
  • If the certificate is invalid or verification fails, the handshake is also terminated
Returns
true if TLS is enabled successfully, server is in encrypted state
false if enabling fails (specific error will be logged)
Warning
After enabling TLS, all incoming connections must follow the TLS handshake process, otherwise communication will fail
See Also
redrawTLS() If a TLS context already exists, it will be released and rebuilt first (can be used for hot updating certificates)
bool stt::network::TcpServer::startListen ( const int &  port,
const int &  threads = 8 
)

Start the TCP server listening program.

Parameters
portPort to listen on
threadsNumber of consumer threads (default is 8)
Returns
true: Listening started successfully, false: Failed to start listening
bool stt::network::TcpServer::stopListen ( )

Stop listening.

Warning
Only stops listening (but the socket can no longer receive, it depends on listening and consumers, so this function is of little significance)
Returns
true: Stopped successfully, false: Failed to stop

Member Data Documentation

unsigned long stt::network::TcpServer::buffer_size
protected
int stt::network::TcpServer::checkFrequency
protected
TcpFDInf* stt::network::TcpServer::clientfd
protected
security::ConnectionLimiter stt::network::TcpServer::connectionLimiter
protected
int stt::network::TcpServer::connectionSecs
protected
int stt::network::TcpServer::connectionTimes
protected
SSL_CTX* stt::network::TcpServer::ctx =nullptr
protected
std::queue<WorkerMessage> stt::network::TcpServer::finishQueue
protected
int stt::network::TcpServer::flag1 =true
protected
unsigned long long stt::network::TcpServer::maxFD
protected
int stt::network::TcpServer::requestSecs
protected
int stt::network::TcpServer::requestTimes
protected
bool stt::network::TcpServer::security_open
protected
int stt::network::TcpServer::serverType
protected
bool stt::network::TcpServer::TLS =false
protected
bool stt::network::TcpServer::unblock
protected
int stt::network::TcpServer::workerEventFD
protected
stt::system::WorkerPool* stt::network::TcpServer::workpool
protected

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