STTNet
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
Public Member Functions | List of all members
stt::network::WebSocketServer Class Reference

WebSocketServer server operation class. More...

#include <sttnet_English.h>

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

Public Member Functions

void putTask (const std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)> &fun, WebSocketServerFDHandler &k, WebSocketFDInformation &inf)
 Submit a task to the worker thread pool. More...
 
 WebSocketServer (const unsigned long long &maxFD=1000000, const int &buffer_size=256, const bool &security_open=true, const int &connectionNumLimit=5, const int &connectionSecs=10, const int &connectionTimes=3, const int &requestSecs=1, const int &requestTimes=10, const int &checkFrequency=60, const int &connectionTimeout=120)
 Constructor. More...
 
void setSecuritySendBackFun (std::function< void(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fc)
 Set the callback invoked when an information security policy is violated. More...
 
void setGlobalSolveFunction (std::function< bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fc)
 Set the global fallback handler. More...
 
void setStartFunction (std::function< bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fccc)
 Set the callback invoked immediately after a WebSocket connection is established. More...
 
void setJudgeFunction (std::function< bool(WebSocketFDInformation &)> fcc)
 Set the handshake validation callback. More...
 
void setFunction (const std::string &key, std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)> fc)
 Register a message handler callback for a specific key. More...
 
void setGetKeyFunction (std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)> parseKeyFun)
 Set the key parsing callback. More...
 
void setTimeOutTime (const int &seca)
 Set heartbeat interval. More...
 
void setHBTimeOutTime (const int &secb)
 Set heartbeat response timeout. More...
 
bool closeFD (const int &fd, const std::string &closeCodeAndMessage)
 Close a WebSocket connection using an encoded close payload. More...
 
bool closeFD (const int &fd, const short &code=1000, const std::string &message="bye")
 Close a WebSocket connection using standard RFC 6455 format. More...
 
bool sendMessage (const int &fd, const std::string &msg, const std::string &type="0001")
 Send a WebSocket message to a specific client. More...
 
bool close ()
 Close all connections and stop listening. More...
 
bool close (const int &fd)
 Close the connection of a certain socket More...
 
bool startListen (const int &port, const int &threads=8)
 Start the WebSocket server. More...
 
void sendMessage (const std::string &msg, const std::string &type="0001")
 Broadcast a WebSocket message to all connected clients. More...
 
 ~WebSocketServer ()
 Destructor. More...
 
- Public Member Functions inherited from stt::network::TcpServer
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...
 
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...
 

Additional Inherited Members

- Protected Attributes inherited from stt::network::TcpServer
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

WebSocketServer server operation class.

Constructor & Destructor Documentation

stt::network::WebSocketServer::WebSocketServer ( const unsigned long long &  maxFD = 1000000,
const int &  buffer_size = 256,
const bool &  security_open = true,
const int &  connectionNumLimit = 5,
const int &  connectionSecs = 10,
const int &  connectionTimes = 3,
const int &  requestSecs = 1,
const int &  requestTimes = 10,
const int &  checkFrequency = 60,
const int &  connectionTimeout = 120 
)
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 introduces 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: 5.
connectionSecsTime window (in seconds) for connection rate limiting. Default: 10 seconds.
connectionTimesMaximum number of connection attempts allowed within connectionSecs seconds. Default: 3.
requestSecsTime window (in seconds) for request/message rate limiting. Default: 1 second.
requestTimesMaximum number of requests/messages allowed within requestSecs seconds. Default: 10.
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: 120 seconds.
stt::network::WebSocketServer::~WebSocketServer ( )
inline

Destructor.

Note
Blocks until all connections, heartbeat threads, and listening sockets are fully closed.

Member Function Documentation

bool stt::network::WebSocketServer::close ( )

Close all connections and stop listening.

Note
This call blocks until all resources are released.
bool stt::network::WebSocketServer::close ( const int &  fd)
virtual

Close the connection of a certain socket

Note
Polymorphism of TcpServer's close for a certain socket

Reimplemented from stt::network::TcpServer.

bool stt::network::WebSocketServer::closeFD ( const int &  fd,
const std::string &  closeCodeAndMessage 
)

Close a WebSocket connection using an encoded close payload.

Parameters
fdSocket file descriptor.
closeCodeAndMessageEncoded close payload (2 bytes close code + optional UTF-8 reason).
Returns
true if closed successfully, false otherwise.
bool stt::network::WebSocketServer::closeFD ( const int &  fd,
const short &  code = 1000,
const std::string &  message = "bye" 
)

Close a WebSocket connection using standard RFC 6455 format.

Parameters
fdSocket file descriptor.
codeWebSocket close code (default: 1000).
messageOptional close reason.
Returns
true if closed successfully, false otherwise.
void stt::network::WebSocketServer::putTask ( const std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)> &  fun,
WebSocketServerFDHandler k,
WebSocketFDInformation inf 
)

Submit a task to the worker thread pool.

Note
Slow or blocking I/O operations should be dispatched to the worker pool.
Warning
The callable object must strictly follow the required return value conventions.
Parameters
funThe callable task to be executed by the worker thread pool.
  • Parameters: WebSocketServerFDHandler &k - Socket operation object bound to the client. WebSocketFDInformation &inf - Client information including data, processing progress, and state machine data.
  • Return value: -2 : Processing failed and the connection must be closed. -1 : Processing failed but the connection should remain open. 1 : Processing succeeded.
kReference to the socket handler.
infReference to the client information.
bool stt::network::WebSocketServer::sendMessage ( const int &  fd,
const std::string &  msg,
const std::string &  type = "0001" 
)
inline

Send a WebSocket message to a specific client.

Parameters
fdClient socket file descriptor.
msgMessage payload.
typeFrame opcode type (default: text frame).
Returns
true if sent successfully, false otherwise.
void stt::network::WebSocketServer::sendMessage ( const std::string &  msg,
const std::string &  type = "0001" 
)

Broadcast a WebSocket message to all connected clients.

Parameters
msgMessage payload.
typeFrame opcode type.
void stt::network::WebSocketServer::setFunction ( const std::string &  key,
std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)>  fc 
)
inline

Register a message handler callback for a specific key.

Note
Multiple handlers can be registered for the same key and will be executed sequentially.
Warning
Return values must strictly follow the defined conventions.
Parameters
keyMessage key.
fcCallback function.
  • Return value: -2 : Close connection. -1 : Processing failed but keep connection. 0 : Dispatched to worker pool. 1 : Processing succeeded.
void stt::network::WebSocketServer::setGetKeyFunction ( std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)>  parseKeyFun)
inline

Set the key parsing callback.

Note
The parsed key must be stored in inf.ctx["key"].
Parameters
parseKeyFunKey parsing function.
void stt::network::WebSocketServer::setGlobalSolveFunction ( std::function< bool(WebSocketServerFDHandler &, WebSocketFDInformation &)>  fc)
inline

Set the global fallback handler.

Note
This handler is invoked when no matching key-based callback is found.
Parameters
fcFallback function to process incoming messages.
void stt::network::WebSocketServer::setHBTimeOutTime ( const int &  secb)
inline

Set heartbeat response timeout.

Parameters
secbTime to wait after sending a heartbeat (seconds).
Note
If no response is received within this time, the connection is closed.
void stt::network::WebSocketServer::setJudgeFunction ( std::function< bool(WebSocketFDInformation &)>  fcc)
inline

Set the handshake validation callback.

Note
Only if this check passes will the WebSocket handshake continue.
Parameters
fccValidation function.
  • Parameters: WebSocketFDInformation &inf
  • Return value: true : Validation passed. false : Validation failed and the connection will be closed.
void stt::network::WebSocketServer::setSecuritySendBackFun ( std::function< void(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)>  fc)
inline

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

This callback is executed when a WebSocket client violates a security rule (e.g. rate limiting, abnormal message behavior, protocol abuse, etc.). After the callback is executed, the connection will be closed.

Note
The callback is invoked once per 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:

  • WebSocketServerFDHandler &k Reference to the handler object that operates on the WebSocket connection/socket.
  • WebSocketFDInformation &inf Client connection information, including buffered data, processing progress, and WebSocket state machine context.
Note
The callback does not return a value. The connection will be closed regardless of the callback outcome.
void stt::network::WebSocketServer::setStartFunction ( std::function< bool(WebSocketServerFDHandler &, WebSocketFDInformation &)>  fccc)
inline

Set the callback invoked immediately after a WebSocket connection is established.

Parameters
fcccCallback executed after successful WebSocket handshake.
void stt::network::WebSocketServer::setTimeOutTime ( const int &  seca)
inline

Set heartbeat interval.

Parameters
secaHeartbeat interval in minutes (default: 20 minutes).
bool stt::network::WebSocketServer::startListen ( const int &  port,
const int &  threads = 8 
)
inline

Start the WebSocket server.

Parameters
portListening port.
threadsNumber of worker threads (default: 8).

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