CRM64Pro GDK v0.16.0
A free cross-platform game development kit built on top of SDL 3.0
Loading...
Searching...
No Matches
Network TCP/IP client/server

Description

Network TCP/IP interface providing a client/server architecture [v26.03.0].

Overview

The Network TCP/IP interface provides a complete TCP client/server communication layer built on top of SDL3_net (SDL_net 3.0.0). It manages connection establishment, login handshake, packet transmission, validation, optional payload protection, queued delivery and runtime statistics through a unified API designed for both stand-alone server deployments and mixed local client+server setups in the same process.

Server modes

Key features

  • Packet framing: DataNet transport over TCP streams using a fixed header plus optional payload
  • Multi-client: Support for up to 8 simultaneous clients
  • Authentication: Challenge/proof login handshake with optional password verification
  • Server validation modes: Authoritative and non-authoritative user data flows
  • Integrity checks: xxHash3-based packet validation
  • Sequencing: PCG-based ordered user packet verification
  • Payload protection: Optional AES-CTR encryption for post-login user traffic
  • Buffered transmission: Outbound queues with pending-write aware soft-brake throttling
  • Diagnostics: Detailed TX/RX, queue, error and latency statistics
  • Flexible deployment: Server can run as stand-alone process or shared with a client instance
  • Async operations: Non-blocking address resolution and connection establishment

Server configuration

Max clientsUp to 8 simultaneous connections
Login systemOptional password authentication (can be enabled or disabled)
DeploymentStand-alone server process or shared with a client instance
BackendSDL3_net (SDL_net 3.0.0) with stream sockets
Payload limitUp to 4 MB per DataNet payload

Transport model

NetTCP uses TCP as a reliable byte stream, but the application never works directly with raw stream bytes. Instead, traffic is wrapped into internal DataNet packets that contain:

  • A sequence value for user packets or generic system data for internal messages
  • The payload size in bytes
  • A packet hash used for integrity checks
  • An internal message identifier
  • The sender client index when relevant
  • An optional payload buffer

The receive side reconstructs each full packet from the stream, validates it, optionally decrypts the payload and then either handles it internally or places it into the application receive queue.

Connection and login flow

The login flow is challenge-based:

  1. The client opens a TCP connection to the server
  2. The server sends a login challenge containing a server nonce and the negotiable session feature flags
  3. The client replies with a login proof derived from the password, nonce and client name
  4. On success, the server returns login acceptance data including a session seed and negotiated features
  5. Both peers derive their session state from the password, server nonce, session seed and client name
  6. After login completes, post-login user packets can use the negotiated protections such as AES-CTR payload encryption

This approach allows per-session cryptographic state to be derived for each connection instead of relying only on a static shared secret.

Server modes

The server supports two working modes depending on how client actions are validated:


Non-authoritative mode

Data processingUser packets are forwarded without gameplay validation
Client rightsEach client has full rights for performing any action
Client behavior"I do my action and report it to others"
Use caseGames where clients do not compete for unique items or actions


Authoritative mode

Data processingQuery packets are evaluated by the server callback and can be accepted or denied
Client rightsClients cannot perform actions until accepted by the server callback
Client behavior"Can I do this action?" → wait for server response → proceed if accepted
Use caseGames where clients compete for unique items or actions

Internal/system packets such as login, disconnect, ping and information updates are handled by the protocol regardless of the selected gameplay validation mode.

Security and integrity

The current implementation provides several transport protections with distinct roles:

xxHash3Fast packet integrity check using the full 64-bit xxHash3 result
PCG sequencerApplied to user packets to detect out-of-sync or otherwise unexpected packet streams
AES-CTROptional payload encryption for post-login user DataNets using login-derived session state and per-packet sequence values
Packet obfuscationLegacy packet-wide XOR layer. Useful as lightweight obfuscation but not a replacement for real session encryption

In practice, this means NetTCP combines session setup, packet integrity checks, ordered user traffic and optional encrypted user payload transport instead of relying on a single monolithic "encrypted/not encrypted" mode.

Queues and throttling

Outgoing application packets are copied into per-side or per-client queues and later flushed by the owner thread. This allows reduced contention on socket access, queue statistics, peak tracking and graceful handling of temporary backpressure.

When pending socket writes for user traffic exceed the configured high watermark, NetTCP temporarily pauses user-packet flushing until the backlog falls below the low watermark. This soft-brake mechanism avoids unbounded packet buildup while keeping the API non-blocking.

Diagnostics and statistics

The module tracks a broad set of runtime diagnostics, including:

  • Total TX/RX bytes
  • User and system packet counters
  • Queue occupancy and queue peaks
  • Current and peak packet sizes
  • Pending socket write estimates
  • Throttling, send failure, bad header and bad payload counters
  • Hash mismatch and sequencer mismatch counters
  • Client latency snapshots and rolling averages

Reading the info() report

The info() report prints live telemetry for the local NetTCP client and/or server instance. The example below shows the full report format and the table describes each field once, indicating whether it appears on the client, the server or both sides.

Example output

[Network Interface] Info:
|  - NetTCP Client v26.03.0:
|    Uptime 143.34 s
|    Features: none
|    Simulated delay 0 ms
|    RX:
|      Queued DataNets: Current 0 - Peak 102/512 - Dropped 0
|      Buffered data: Queue 0 B (peak 3 MB) - Handed to app 0 B - Current DataNet 0 B (peak 3 MB)
|      DataNets: System 148 - User 1428168
|      Data volume: Total 7.91 GB - Throughput 56.49 MB/s
|      Average DataNet size: System 25 B - User 5.81 KB
|      Errors: Bad header 0 - Bad data 0 - Hash 0 - Sequencer 0
|    TX:
|      Queued DataNets: Current 0 - Peak 1/512
|      TX throttle: High 256.00 KB - Low 128.00 KB
|      Buffered data: Queue 0 B (peak 0 B) - Socket pending 0 B - Total pending 0 B - Current DataNet 0 B (peak 24 B)
|      DataNets: System 145 - User 0
|      Data volume: Total 3.42 KB - Throughput 24 B/s
|      Average DataNet size: System 24 B - User 0 B
|      Errors: Throttled 0 - Limit 0 - Send fail 0
|
|  - NetTCP Server v26.03.0:
|    Uptime 143.38 s
|    Features: none
|    Connected clients: 2
|    Latency: Avg 2 ms - Max 2 ms
|    RX:
|      Buffered data: Current DataNet 0 B (peak 3 MB)
|      DataNets: System 288 - User 1428168
|      Data volume: Total 7.91 GB - Throughput 56.47 MB/s
|      Average DataNet size: System 24 B - User 5.81 KB
|      Errors: Bad header 0 - Bad data 0 - Hash 0 - Sequencer 0
|    TX:
|      Queued DataNets: Current avg 0 - Current max 0 - Peak max 1/512
|      TX throttle: High 256.00 KB - Low 128.00 KB
|      Buffered data: Queue avg 0 B - Queue max 0 B - Queue peak 3 MB - Current DataNet 0 B (peak 3 MB)
|      DataNets: System 292 - User 2856336
|      Data volume: Total 15.81 GB - Throughput 112.95 MB/s
|      Average DataNet size: System 25 B - User 5.81 KB
|      Errors: Throttled 0 - Limit 0 - Send fail 0

Field reference

FieldScopeMeaning
UptimeBothTime elapsed since the local NetTCP client or server instance started running.
FeaturesBothFeature state reported for that side. On the client this shows negotiated session features; on the server it shows the locally configured server feature flags.
Simulated delayClientArtificial client-side delay in milliseconds used for testing latency-sensitive code paths.
Connected clientsServerNumber of clients currently connected to the local server.
Latency: Avg / MaxServerAggregate latency summary across currently connected clients. It is useful as a quick health indicator, not a substitute for per-client inspection.
RX > Queued DataNetsClientReceive queue population. Current is the number of packets waiting for the application, Peak is the highest observed queue usage and Dropped counts packets discarded because the queue was full.
RX > Buffered dataBothByte usage in the receive path. On the client, Queue is the queued byte count, peak is its high-water mark and Handed to app counts bytes delivered through receiveData() but not yet released with freeData(). On both client and server, Current DataNet is the size of the packet currently being assembled or processed and peak is the largest packet seen in the RX path.
RX > DataNetsBothCount of received packets split into System protocol packets and User application packets.
RX > Data volumeBothTotal is the number of received bytes since startup, including headers and payloads. Throughput is the average receive rate since startup shown in human-readable form.
RX > Average DataNet sizeBothAverage size of received System packets and received User packets.
RX > ErrorsBothBad header counts malformed, incomplete or timed-out packet headers. Bad data counts malformed, incomplete or timed-out payloads. Hash counts integrity mismatches. Sequencer counts user packets rejected because the expected PCG sequence value did not match.
TX > Queued DataNetsClient, ServerTransmit queue population. On the client, Current is the number of outbound packets currently queued and Peak is the highest observed queue usage. On the server, Current avg is the average queued outbound packet count across connected clients, Current max is the highest current queue population among them and Peak max is the highest per-client queue population observed since startup.
TX > TX throttleBothSoft-brake watermarks used to pause user-packet flushing when pending writes grow too large and to resume once the backlog falls again.
TX > Buffered dataClient, ServerByte usage in the transmit path. On the client, Queue is the queued byte count, peak is its high-water mark, Socket pending is the amount already handed to the SDL3_net socket and Total pending is queue plus socket backlog. On the server, Queue avg is the average queued outbound bytes across connected clients, Queue max is the largest current queued byte count among them and Queue peak is the highest per-client queued byte usage observed since startup. On both sides, Current DataNet is the size of the packet currently being prepared or flushed and peak is the largest packet seen in the TX path.
TX > DataNetsBothCount of transmitted packets split into System protocol packets and User application packets.
TX > Data volumeBothTotal is the number of transmitted bytes since startup, including headers and payloads. Throughput is the average transmit rate since startup shown in human-readable form.
TX > Average DataNet sizeBothAverage size of transmitted System packets and transmitted User packets.
TX > ErrorsBothThrottled counts send attempts deferred because transmission was temporarily backpressured. Limit counts send attempts rejected because packet or queue limits were reached before transmission. Send fail counts low-level transmission failures after a packet had already entered the TX path.

Best practices

  • Choose the appropriate server mode based on your game design requirements
  • Use authoritative mode when clients compete for unique resources to prevent race conditions
  • Design callback functions carefully in authoritative mode to avoid impossible situations
  • Enable AES-CTR only when you need protected post-login user payloads
  • Treat ::NR_TX_THROTTLED as a retry-later condition instead of a fatal error
  • Call receiveData() repeatedly until ::NM_NOTHING is returned
  • Query client info explicitly when up-to-date latency snapshots are required
  • Use the statistics, queue metrics and pending-write information to tune soft-brake thresholds
  • Consider running the server as a stand-alone process for production deployments
  • Access the interface exclusively through Main::INetTCP()
Note
The Network TCP/IP interface is a singleton, automatically created once Main is instantiated. You can get a reference to this interface using Main::INetTCP() method.
The Network TCP/IP interface is automatically released when Main::Terminate() is called. At this time, any resource still loaded will be released, avoiding resource leaks.

Classes

class  CRM64Pro::NetTCP
 NetTCP class. More...

Enumerations

enum  CRM64Pro::eNetMsg {
  CRM64Pro::NM_NOTHING = 0 , CRM64Pro::NM_DATA = 64 , CRM64Pro::NM_DATA_ACCEPTED = 66 , CRM64Pro::NM_DATA_DENIED = 67 ,
  CRM64Pro::NM_NEWCLIENT = 132 , CRM64Pro::NM_QUITCLIENT = 133 , CRM64Pro::NM_CLOSE = 134 , CRM64Pro::NM_INFO = 135 ,
  CRM64Pro::NM_PING = 136 , CRM64Pro::NM_ERROR = 192
}
 Network messages. More...
enum  CRM64Pro::eNetResult {
  CRM64Pro::NR_OK = 0 , CRM64Pro::NR_NO_INIT = -1 , CRM64Pro::NR_IS_INIT = -2 , CRM64Pro::NR_ABORT = -3 ,
  CRM64Pro::NR_CAN_NOT_CONNECT = -4 , CRM64Pro::NR_NO_SERVER_RUNNING = -10 , CRM64Pro::NR_NO_CLIENT_RUNNING = -11 , CRM64Pro::NR_ONLY_ONE_SERVER = -12 ,
  CRM64Pro::NR_ONLY_ONE_CLIENT = -13 , CRM64Pro::NR_WRONG_PORT = -14 , CRM64Pro::NR_OUT_OF_MEMORY = -15 , CRM64Pro::NR_TX_EMPTY_DN = -16 ,
  CRM64Pro::NR_INVALID_CLIENT = -20 , CRM64Pro::NR_DUPLICATED_CLIENT = -22 , CRM64Pro::NR_CLIENT_LIMIT_REACHED = -23 , CRM64Pro::NR_WRONG_PASSWORD = -24 ,
  CRM64Pro::NR_LOGIN_DISABLED = -25 , CRM64Pro::NR_BAD_PARAMETER = -26 , CRM64Pro::NR_RX_LIMIT_REACHED = -29 , CRM64Pro::NR_TX_THROTTLED = -30 ,
  CRM64Pro::NR_CREATE_THREAD = -31 , CRM64Pro::NR_CLIENT_INTERNAL = -100 , CRM64Pro::NR_SERVER_INTERNAL = -300 , CRM64Pro::NR_HASH_MISMATCH = -512 ,
  CRM64Pro::NR_SEQUENCER_MISMATCH = -1024 , CRM64Pro::NR_SDLNET_INIT = -2048 , CRM64Pro::NR_RX_BAD_HEADER = -2049 , CRM64Pro::NR_RX_BAD_DATA = -2050 ,
  CRM64Pro::NR_TX_BAD_DATA = -2051 , CRM64Pro::NR_RESOLVE_HOST = -4096 , CRM64Pro::NR_TCP_OPEN = -4097 , CRM64Pro::NR_ALLOCATE_SOCKET = -4098 ,
  CRM64Pro::NR_ADD_SOCKET = -4099 , CRM64Pro::NR_CHECK_SOCKET = -4100
}
 Network result codes. More...
enum  CRM64Pro::eNetTCPFeature : Uint32 { CRM64Pro::NTF_DISABLE = 0 , CRM64Pro::NTF_DISABLE_LOGIN = 1 , CRM64Pro::NTF_AES_CTR = 2 }
 NetTCP feature flags. More...

Functions

bool CRM64Pro::NetTCP::info (Sint32 iMode=0) override
 Request NetTCP Interface information.
eNetResult CRM64Pro::NetTCP::init (eLogMode eLM)
 Initialize the NetTCP system.
eNetResult CRM64Pro::NetTCP::close ()
 Close the NetTCP system.
bool CRM64Pro::NetTCP::isServer () const
 Check if the server is running.
bool CRM64Pro::NetTCP::isClient () const
 Check if the client is running.
NetIPAddress CRM64Pro::NetTCP::getIP () const
 Get the IP address.
eNetResult CRM64Pro::NetTCP::getClientName (string &sClientName) const
 Get the client name.
bool CRM64Pro::NetTCP::setFeatures (eNetTCPFeature eNF, bool bEnable)
 Set advanced features.
eNetTCPFeature CRM64Pro::NetTCP::getFeatures () const
 Get advanced features.
eNetResult CRM64Pro::NetTCP::connectTo (const string &sHost, Uint16 iPort, const string &sClient, const string &sPassword)
 Connect to a server.
eNetResult CRM64Pro::NetTCP::sendData (void *pData, Sint32 iSize, Uint8 bIsQuery=1)
 Send a data package.
eNetMsg CRM64Pro::NetTCP::receiveData (void **pData, Uint32 *iSize, Uint8 *senderID=nullptr)
 Receive a data package (non-blocking method).
eNetResult CRM64Pro::NetTCP::freeData (void *&pData)
 Free a received data package.
eNetResult CRM64Pro::NetTCP::queryKillServer ()
 Query to close the server (and all the connected clients).
eNetResult CRM64Pro::NetTCP::queryKillClient ()
 Query to kill this client.
eNetResult CRM64Pro::NetTCP::queryClientsInfo ()
 Query to get updated the information of all connected clients.
Sint32 CRM64Pro::NetTCP::getPendingWrites () const
 Query pending outgoing bytes on the local client stream socket.
eNetResult CRM64Pro::NetTCP::setTXSoftBrake (Uint32 iHighWater, Uint32 iLowWater)
 Set TX soft-brake watermarks used by the owner-thread flush loops.
eNetResult CRM64Pro::NetTCP::getTXSoftBrake (Uint32 *iHighWater, Uint32 *iLowWater) const
 Get TX soft-brake watermarks currently used by NetTCP.
Sint32 CRM64Pro::NetTCP::getClientsInfo (ClientInfo **cinfo)
 Get information stored locally about all connected clients.
Sint32 CRM64Pro::NetTCP::setTimeOut (Sint32 iMs)
 Set the connection timeout.
Sint32 CRM64Pro::NetTCP::setSimDelay (Sint32 iMs, Sint32 iMode=0)
 Simulate a connection delay.
eNetResult CRM64Pro::NetTCP::createServer (Uint16 iPort, const string &sPassword, Sint32 iDedicated)
 Create a server.
eNetResult CRM64Pro::NetTCP::setCoreServerCallback (Sint32(*myCoreServer)(void *pData, Sint32 iSize, void *pObj), void *pObj=nullptr)
 Set a callback function into the server thread for handling data.

Enumeration Type Documentation

◆ eNetMsg

Network messages.

Enumerator
NM_NOTHING 

No message received.

NM_DATA 

User data received, pData has it.

NM_DATA_ACCEPTED 

Data sent by us was accepted, pData has it.

NM_DATA_DENIED 

Data sent by us was denied, pData has it.

NM_NEWCLIENT 

New client connected, pData has the client name.

NM_QUITCLIENT 

A client has exited, pData has the client name.

NM_CLOSE 

Server has closed us.

NM_INFO 

After request a fresh client info, it has arrived and ready to be checked with getClientsInfo().

NM_PING 

Periodic ping sent by the server.

NM_ERROR 

Error, it usually means the client lost the connection with the server.

◆ eNetResult

Network result codes.

Enumerator
NR_OK 

Operation completed successfully.

NR_NO_INIT 

NetTCP is not initialized.

NR_IS_INIT 

NetTCP is already initialized.

NR_ABORT 

Operation aborted.

NR_CAN_NOT_CONNECT 

Connection could not be established.

NR_NO_SERVER_RUNNING 

No server is currently running.

NR_NO_CLIENT_RUNNING 

No client is currently running.

NR_ONLY_ONE_SERVER 

Only one server can run at a time.

NR_ONLY_ONE_CLIENT 

Only one client can run at a time.

NR_WRONG_PORT 

Invalid TCP port.

NR_OUT_OF_MEMORY 

Memory allocation failed.

NR_TX_EMPTY_DN 

Empty DataNet payload is not allowed.

NR_INVALID_CLIENT 

Invalid client name or state.

NR_DUPLICATED_CLIENT 

Client name is already in use.

NR_CLIENT_LIMIT_REACHED 

Maximum number of clients reached.

NR_WRONG_PASSWORD 

Wrong server password.

NR_LOGIN_DISABLED 

Server logins are currently disabled.

NR_BAD_PARAMETER 

Invalid parameter.

NR_RX_LIMIT_REACHED 

RX queue limit reached.

NR_TX_THROTTLED 

Outgoing traffic is temporarily throttled/backpressured. Retry later.

NR_CREATE_THREAD 

Failed to create the worker thread.

NR_CLIENT_INTERNAL 

Internal client-side failure.

NR_SERVER_INTERNAL 

Internal server-side failure.

NR_HASH_MISMATCH 

Received DataNet failed hash validation.

NR_SEQUENCER_MISMATCH 

Received DataNet failed sequencer validation.

NR_SDLNET_INIT 

SDL3_net initialization failed.

NR_RX_BAD_HEADER 

Failed to receive a valid DataNet header.

NR_RX_BAD_DATA 

Failed to receive the full DataNet payload.

NR_TX_BAD_DATA 

Failed to transmit a DataNet.

NR_RESOLVE_HOST 

Hostname resolution failed.

NR_TCP_OPEN 

Failed to open the TCP connection.

NR_ALLOCATE_SOCKET 

Failed to allocate socket resources.

NR_ADD_SOCKET 

Failed to add the socket to the monitoring set.

NR_CHECK_SOCKET 

Failed while checking socket status.

◆ eNetTCPFeature

enum CRM64Pro::eNetTCPFeature : Uint32

NetTCP feature flags.

Enumerator
NTF_DISABLE 

Disable all NetTCP features. Default value.

NTF_DISABLE_LOGIN 

Disable new client logins to the server.

NTF_AES_CTR 

Enable AES-CTR payload encryption for post-login user DataNets.

Function Documentation

◆ info()

bool CRM64Pro::NetTCP::info ( Sint32 iMode = 0)
override

Request NetTCP Interface information.

Writes runtime NetTCP diagnostics to the default log, including TX/RX counters, queue usage, latency and feature state.

Parameters
iModeunused for the time being.
Returns
true on success, or false on failure.

◆ init()

eNetResult CRM64Pro::NetTCP::init ( eLogMode eLM)

Initialize the NetTCP system.

Before using createServer() or connectTo(), NetTCP must be initialized.

Parameters
eLMdedicated network log mode. Check LM_NULL, LM_STDOUT, LM_FILE, LM_FILEAPPEND and LM_CONSOLE (can be OR'ed). Default is LM_NULL.
Returns
::NR_OK on success, or another ::eNetResult on failure.

◆ close()

eNetResult CRM64Pro::NetTCP::close ( )

Close the NetTCP system.

Returns
::NR_OK on success, or another ::eNetResult on failure.

◆ isServer()

bool CRM64Pro::NetTCP::isServer ( ) const

Check if the server is running.

Returns
false if server is not running or true when it is.

◆ isClient()

bool CRM64Pro::NetTCP::isClient ( ) const

Check if the client is running.

Returns
false if client is not running or true when it is.

◆ getIP()

NetTCP::NetIPAddress CRM64Pro::NetTCP::getIP ( ) const

Get the IP address.

Returns
numeric local address information for the running client or server.

◆ getClientName()

eNetResult CRM64Pro::NetTCP::getClientName ( string & sClientName) const

Get the client name.

Parameters
sClientNamea string containing the client name when it is connected to a server.
Returns
::NR_OK on success, or another ::eNetResult on failure.

◆ setFeatures()

bool CRM64Pro::NetTCP::setFeatures ( eNetTCPFeature eNF,
bool bEnable )

Set advanced features.

Parameters
eNFone or more NetTCP features to modify.
bEnabletrue to enable the features, false to disable them.
Returns
true on success or false on failure.

◆ getFeatures()

eNetTCPFeature CRM64Pro::NetTCP::getFeatures ( ) const

Get advanced features.

Returns
current NetTCP feature flags.

◆ connectTo()

eNetResult CRM64Pro::NetTCP::connectTo ( const string & sHost,
Uint16 iPort,
const string & sClient,
const string & sPassword )

Connect to a server.

This method attempts to connect to the server during the timeout configured by setTimeOut(). After the TCP connection is established, NetTCP completes the login handshake before returning success.

Parameters
sHosthost name or IP of the server to connect to.
iPortthe listening server port (1024 to 65535).
sClientclient name, must be unique and with a maximum of 16 characters.
sPasswordpassword/passphrase to connect to the server. Maximum length is 64 characters.
Returns
::NR_OK on success, or another ::eNetResult on failure.

◆ sendData()

eNetResult CRM64Pro::NetTCP::sendData ( void * pData,
Sint32 iSize,
Uint8 bIsQuery = 1 )

Send a data package.

Sends an application payload from the local client to the connected server. In authoritative mode, user packets are evaluated by the CoreServer callback and can be accepted or denied. In non-authoritative mode, user packets are redistributed by the server without callback validation.

Parameters
pDatapointer to your data.
iSizesize in bytes of your data.
bIsQueryfor authoritative mode only. Default 1 allows callback evaluation. Other values bypass evaluation.
Returns
::NR_OK on success, ::NR_TX_THROTTLED when transmission is temporarily backpressured, or another ::eNetResult on failure.

◆ receiveData()

eNetMsg CRM64Pro::NetTCP::receiveData ( void ** pData,
Uint32 * iSize,
Uint8 * senderID = nullptr )

Receive a data package (non-blocking method).

Data packages come from server or other clients. Incoming packages are queued; call repeatedly until ::NM_NOTHING is returned.

Parameters
pDatapointer to received data package.
iSizepointer to integer with size of received data.
senderIDoptional pointer to receive the sender's client ID for user DataNets. Pass nullptr if not needed.
Returns
an ::eNetMsg value. When ::NM_NOTHING is returned, pData is nullptr and iSize is 0.
Note
Data is auto-allocated but after receiving via this method, YOU MUST call freeData() when done to avoid memory leaks.

◆ freeData()

eNetResult CRM64Pro::NetTCP::freeData ( void *& pData)

Free a received data package.

Release a payload previously returned by receiveData(). Do not use any other deallocation function for this memory.

Parameters
pDatapointer to the received data.
Returns
::NR_OK on success, or another ::eNetResult on failure.

◆ queryKillServer()

eNetResult CRM64Pro::NetTCP::queryKillServer ( )

Query to close the server (and all the connected clients).

Requests a graceful server shutdown. If a local client is connected, the request is sent to the server. If only a local server is running, shutdown begins immediately.

Returns
::NR_OK on success, ::NR_TX_THROTTLED when transmission is temporarily backpressured, or another ::eNetResult on failure.
Note
Connected clients will normally receive ::NM_CLOSE during shutdown.

◆ queryKillClient()

eNetResult CRM64Pro::NetTCP::queryKillClient ( )

Query to kill this client.

Requests a graceful disconnection of the local client from the server.

Returns
::NR_OK on success, ::NR_TX_THROTTLED when transmission is temporarily backpressured, or another ::eNetResult on failure.
Note
This does not imply that receiveData() will return an error; peers will usually observe a normal disconnect sequence.

◆ queryClientsInfo()

eNetResult CRM64Pro::NetTCP::queryClientsInfo ( )

Query to get updated the information of all connected clients.

Returns
::NR_OK on success, ::NR_TX_THROTTLED when transmission is temporarily backpressured, or another ::eNetResult on failure.

◆ getPendingWrites()

Sint32 CRM64Pro::NetTCP::getPendingWrites ( ) const

Query pending outgoing bytes on the local client stream socket.

Returns
number of bytes pending transmission on success, or a negative ::eNetResult on failure.

◆ setTXSoftBrake()

eNetResult CRM64Pro::NetTCP::setTXSoftBrake ( Uint32 iHighWater,
Uint32 iLowWater )

Set TX soft-brake watermarks used by the owner-thread flush loops.

When pending socket writes for user traffic reach the high watermark, NetTCP temporarily pauses further user-packet flushing until the backlog drops to the low watermark. Control/login traffic is not affected by this soft-brake.

Parameters
iHighWaterhigh watermark in bytes. Must be >= low watermark.
iLowWaterlow watermark in bytes. Must be <= high watermark.
Returns
::NR_OK on success, or another ::eNetResult on failure.

◆ getTXSoftBrake()

eNetResult CRM64Pro::NetTCP::getTXSoftBrake ( Uint32 * iHighWater,
Uint32 * iLowWater ) const

Get TX soft-brake watermarks currently used by NetTCP.

Parameters
iHighWateroutput pointer to receive the high watermark in bytes.
iLowWateroutput pointer to receive the low watermark in bytes.
Returns
::NR_OK on success, or another ::eNetResult on failure.

◆ getClientsInfo()

Sint32 CRM64Pro::NetTCP::getClientsInfo ( ClientInfo ** cinfo)

Get information stored locally about all connected clients.

Client info table auto-updates on connect/disconnect. For real latency, call queryClientsInfo() first (not needed if client runs with server).

Parameters
cinfopointer to the local ClientInfo table.
Returns
positive integer with number of clients on success, or a negative ::eNetResult on failure.

◆ setTimeOut()

Sint32 CRM64Pro::NetTCP::setTimeOut ( Sint32 iMs)

Set the connection timeout.

Sets the base network timeout used by hostname resolution, TCP connect, client login waits, server pending-login lifetime and RX partial-read progress watchdogs. Login waits use the configured timeout, server pending-logins use twice that value and partial-read progress uses max(1000 ms, iMs / 2).

Parameters
iMstimeout in milliseconds. Minimum 500ms. Default 2000ms.
Returns
0 on success, or -1 if the value is outside the accepted range.

◆ setSimDelay()

Sint32 CRM64Pro::NetTCP::setSimDelay ( Sint32 iMs,
Sint32 iMode = 0 )

Simulate a connection delay.

Only works for clients. Can be changed at any time.

Parameters
iMssimulated delay in milliseconds [0-2500]. Default 0.
iModeReserved for future use.
Returns
0 on success, or -1 if the value is outside the accepted range.

◆ createServer()

eNetResult CRM64Pro::NetTCP::createServer ( Uint16 iPort,
const string & sPassword,
Sint32 iDedicated )

Create a server.

Parameters
iPortthe listening server port (1024 to 65535).
sPasswordserver password/passphrase. Maximum length is 64 characters.
iDedicated1 for stand-alone mode (call blocks until server closes). 0 for threaded mode (call returns immediately).
Returns
::NR_OK on success, or another ::eNetResult on failure.
Note
Only one server can be created.

◆ setCoreServerCallback()

eNetResult CRM64Pro::NetTCP::setCoreServerCallback ( Sint32(* myCoreServer )(void *pData, Sint32 iSize, void *pObj),
void * pObj = nullptr )

Set a callback function into the server thread for handling data.

Parameters
myCoreServercallback function taking data pointer, size, and optional pObj. When this callback is set, the server runs in authoritative mode. Use nullptr to disable it and return to non-authoritative mode. The callback runs on the server thread. Return 0 to accept the user packet or a negative value to deny it.
pObjpointer to data/function/static method. Default nullptr (unused).
Returns
::NR_OK on success, or another ::eNetResult on failure.