| CRM64Pro GDK v0.19.0 A free cross-platform game development kit built on top of SDL 3.0

Loading...
Searching...
No Matches
Network TCP
Network modules

## Description

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

Server modes

### Overview

The Network TCP/IP module 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.

### 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 backpressure 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 clients | Up to 8 simultaneous connections
Login system | Optional password authentication (can be enabled or disabled)
Deployment | Stand-alone server process or shared with a client instance
Backend | SDL3_net (SDL_net 3.0.0) with stream sockets
Payload limit | Up 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 processing | User packets are forwarded without gameplay validation
Client rights | Each client has full rights for performing any action
Client behavior | "I do my action and report it to others"
Use case | Games where clients do not compete for unique items or actions

Authoritative mode

Data processing | Query packets are evaluated by the server callback and can be accepted or denied
Client rights | Clients cannot perform actions until accepted by the server callback
Client behavior | "Can I do this action?" → wait for server response → proceed if accepted
Use case | Games 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:

xxHash3 | Fast packet integrity check using the full 64-bit xxHash3 result
PCG sequencer | Applied to user packets to detect out-of-sync or otherwise unexpected packet streams
AES-CTR | Optional payload encryption for post-login user DataNets using login-derived session state and per-packet sequence values
Packet obfuscation | Legacy 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 backpressure 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 Module] 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

Field | Scope | Meaning
--- | --- | ---
Uptime | Both | Time elapsed since the local NetTCP client or server instance started running.
Features | Both | Feature 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 delay | Client | Artificial client-side delay in milliseconds used for testing latency-sensitive code paths.
Connected clients | Server | Number of clients currently connected to the local server.
Latency: Avg / Max | Server | Aggregate latency summary across currently connected clients. It is useful as a quick health indicator, not a substitute for per-client inspection.
RX > Queued DataNets | Client | Receive 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 data | Both | Byte 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 > DataNets | Both | Count of received packets split into System protocol packets and User application packets.
RX > Data volume | Both | Total 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 size | Both | Average size of received System packets and received User packets.
RX > Errors | Both | Bad 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 DataNets | Client, Server | Transmit 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 throttle | Both | Backpressure watermarks used to pause user-packet flushing when pending writes grow too large and to resume once the backlog falls again.
TX > Buffered data | Client, Server | Byte 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 > DataNets | Both | Count of transmitted packets split into System protocol packets and User application packets.
TX > Data volume | Both | Total 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 size | Both | Average size of transmitted System packets and transmitted User packets.
TX > Errors | Both | Throttled 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 backpressure thresholds
- Consider running the server as a stand-alone process for production deployments
- Access the module exclusively through Main::netTCP()

Note
  The Network TCP/IP module is a singleton, automatically created once Main is instantiated. You can get a reference to this module using Main::netTCP() method.
  The Network TCP/IP module 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 : Sint32 { 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 : Sint32 { CRM64Pro::NR_OK = 0 , CRM64Pro::NR_BAD_PARAMETER = C64_ERR_PARAM , CRM64Pro::NR_OUT_OF_MEMORY = C64_ERR_ALLOC , CRM64Pro::NR_NO_INIT = -0x10000 , CRM64Pro::NR_IS_INIT = -0x10001 , CRM64Pro::NR_ABORT = -0x10002 , CRM64Pro::NR_CAN_NOT_CONNECT = -0x10003 , CRM64Pro::NR_NO_SERVER_RUNNING = -0x10004 , CRM64Pro::NR_NO_CLIENT_RUNNING = -0x10005 , CRM64Pro::NR_ONLY_ONE_SERVER = -0x10006 , CRM64Pro::NR_ONLY_ONE_CLIENT = -0x10007 , CRM64Pro::NR_WRONG_PORT = -0x10008 , CRM64Pro::NR_TX_EMPTY_DN = -0x10009 , CRM64Pro::NR_INVALID_CLIENT = -0x10020 , CRM64Pro::NR_DUPLICATED_CLIENT = -0x10021 , CRM64Pro::NR_CLIENT_LIMIT_REACHED = -0x10022 , CRM64Pro::NR_WRONG_PASSWORD = -0x10023 , CRM64Pro::NR_LOGIN_DISABLED = -0x10024 , CRM64Pro::NR_RX_LIMIT_REACHED = -0x10040 , CRM64Pro::NR_TX_THROTTLED = -0x10041 , CRM64Pro::NR_CREATE_THREAD = -0x10042 , CRM64Pro::NR_CLIENT_INTERNAL = -0x10060 , CRM64Pro::NR_SERVER_INTERNAL = -0x10061 , CRM64Pro::NR_HASH_MISMATCH = -0x10062 , CRM64Pro::NR_SEQUENCER_MISMATCH = -0x10063 , CRM64Pro::NR_SDLNET_INIT = -0x10080 , CRM64Pro::NR_RX_BAD_HEADER = -0x10081 , CRM64Pro::NR_RX_BAD_DATA = -0x10082 , CRM64Pro::NR_TX_BAD_DATA = -0x10083 , CRM64Pro::NR_RESOLVE_HOST = -0x100A0 , CRM64Pro::NR_TCP_OPEN = -0x100A1 , CRM64Pro::NR_ALLOCATE_SOCKET = -0x100A2 , CRM64Pro::NR_ADD_SOCKET = -0x100A3 , CRM64Pro::NR_CHECK_SOCKET = -0x100A4 }
| 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 module 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 (const void *pData, Sint32 iSize, bool bIsQuery=true)
| Send a data package.
eNetMsg | CRM64Pro::NetTCP::receiveData (void **ppData, Uint32 *iSize, Uint8 *pSenderIdx=nullptr)
| Receive a data package (non-blocking method).
eNetResult | CRM64Pro::NetTCP::freeData (void *&pData)
| Free a received data package.
eNetResult | CRM64Pro::NetTCP::requestServerClose ()
| Request server shutdown.
eNetResult | CRM64Pro::NetTCP::requestClientClose ()
| Request local client disconnection.
eNetResult | CRM64Pro::NetTCP::queryClientsInfo ()
| Request updated information for all connected clients.
eNetResult | CRM64Pro::NetTCP::getPendingWrites (Uint32 *iBytes) const
| Query pending outgoing bytes on the local client stream socket.
eNetResult | CRM64Pro::NetTCP::setTXBackpressure (Uint32 iHighWater, Uint32 iLowWater)
| Set TX backpressure watermarks used by the owner-thread flush loops.
TXBackpressure | CRM64Pro::NetTCP::getTXBackpressure () const
| Get TX backpressure watermarks currently used by NetTCP.
eNetResult | CRM64Pro::NetTCP::getClientsInfo (ClientInfo **ppClientInfo, Sint32 *iCount)
| Get the local client information snapshot.
eNetResult | CRM64Pro::NetTCP::setTimeout (Sint32 iMs)
| Set the connection timeout.
Sint32 | CRM64Pro::NetTCP::getTimeout () const
| Get the connection timeout.
eNetResult | CRM64Pro::NetTCP::setSimDelay (Sint32 iMs)
| Simulate a connection delay.
Sint32 | CRM64Pro::NetTCP::getSimDelay () const
| Get the simulated connection delay.
eNetResult | CRM64Pro::NetTCP::createServer (Uint16 iPort, const string &sPassword, bool bDedicated)
| Create a server.
eNetResult | CRM64Pro::NetTCP::setCoreServerCallback (Sint32(*fnCallback)(void *pData, Sint32 iSize, void *pUser), void *pUser=nullptr)
| Set a callback function into the server thread for handling data.

## Enumeration Type Documentation

## ◆ eNetMsg

enum CRM64Pro::eNetMsg : Sint32

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 | Fresh client information is available after queryClientsInfo() and can be read 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

enum CRM64Pro::eNetResult : Sint32

Network result codes.

NetTCP uses a dedicated error range for network-specific failures. Only exact generic failures reuse ::C64_ERR_PARAM and ::C64_ERR_ALLOC.

Enumerator
NR_OK | Operation completed successfully.
NR_BAD_PARAMETER | Invalid parameter.
NR_OUT_OF_MEMORY | Memory allocation failed.
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_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_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 module information.

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

Parameters

  iMode | Reserved for future use. Pass 0.

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

  eLM | dedicated 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 a negative ::eNetResult on failure.

## ◆ close()

eNetResult CRM64Pro::NetTCP::close | ( |  | ) |

Close the NetTCP system.

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

## ◆ isServer()

bool CRM64Pro::NetTCP::isServer | ( |  | ) | const

Check if the server is running.

Returns
  true if the server is running, or false otherwise.

## ◆ isClient()

bool CRM64Pro::NetTCP::isClient | ( |  | ) | const

Check if the client is running.

Returns
  true if the client is running, or false otherwise.

## ◆ 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

  sClientName | a string containing the client name when it is connected to a server.

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

## ◆ setFeatures()

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

Set advanced features.

Parameters

  eNF | one or more NetTCP features to modify.
  bEnable | true to enable the features, false to disable them.

Note
  NTF_AES_CTR is lightweight protection for trusted or casual networks: NetTCP derives login/session material with xxHash3 and uses non-authenticated AES-CTR, so it is not suitable against active attackers.

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

  sHost | host name or IP of the server to connect to.
  iPort | the listening server port (1024 to 65535).
  sClient | client name, must be unique and with a maximum of 16 characters.
  sPassword | password/passphrase to connect to the server. Maximum length is 64 characters.

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

## ◆ sendData()

eNetResult CRM64Pro::NetTCP::sendData | ( | const void * | pData,
|  | Sint32 | iSize,
|  | bool | bIsQuery = true )

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

  pData | pointer to the data to send. The data is copied before the method returns.
  iSize | size in bytes of your data.
  bIsQuery | true to allow authoritative callback evaluation, false to bypass evaluation.

Returns
  ::NR_OK on success, ::NR_TX_THROTTLED when retry is required, or another negative ::eNetResult on failure.

## ◆ receiveData()

eNetMsg CRM64Pro::NetTCP::receiveData | ( | void ** | ppData,
|  | Uint32 * | iSize,
|  | Uint8 * | pSenderIdx = 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

  ppData | Output owned payload pointer, or nullptr when no data is available.
  iSize | pointer to integer with size of received data.
  pSenderIdx | optional pointer to receive the sender client index for user DataNets. Pass nullptr if not needed.

Returns
  an ::eNetMsg value. When ::NM_NOTHING is returned, ppData is nullptr and iSize is 0.

Note
  The returned payload must be released with freeData().

## ◆ 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

  pData | Owned payload pointer returned by receiveData(). Set to nullptr on success.

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

## ◆ requestServerClose()

eNetResult CRM64Pro::NetTCP::requestServerClose | ( |  | ) |

Request server shutdown.

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 retry is required, or another negative ::eNetResult on failure.

Note
  Connected clients will normally receive ::NM_CLOSE during shutdown.

## ◆ requestClientClose()

eNetResult CRM64Pro::NetTCP::requestClientClose | ( |  | ) |

Request local client disconnection.

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

Returns
  ::NR_OK on success, ::NR_TX_THROTTLED when retry is required, or another negative ::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 | ( |  | ) |

Request updated information for all connected clients.

Returns
  ::NR_OK on success, ::NR_TX_THROTTLED when retry is required, or another negative ::eNetResult on failure.

## ◆ getPendingWrites()

eNetResult CRM64Pro::NetTCP::getPendingWrites | ( | Uint32 * | iBytes | ) | const

Query pending outgoing bytes on the local client stream socket.

Parameters

  iBytes | pointer to receive the number of bytes pending transmission [0,n].

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

## ◆ setTXBackpressure()

eNetResult CRM64Pro::NetTCP::setTXBackpressure | ( | Uint32 | iHighWater,
|  | Uint32 | iLowWater )

Set TX backpressure 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 backpressure.

Parameters

  iHighWater | high watermark in bytes. Must be >= low watermark.
  iLowWater | low watermark in bytes. Must be <= high watermark.

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

## ◆ getTXBackpressure()

NetTCP::TXBackpressure CRM64Pro::NetTCP::getTXBackpressure | ( |  | ) | const

Get TX backpressure watermarks currently used by NetTCP.

Returns
  Current TX backpressure watermark configuration.

## ◆ getClientsInfo()

eNetResult CRM64Pro::NetTCP::getClientsInfo | ( | ClientInfo ** | ppClientInfo,
|  | Sint32 * | iCount )

Get the local client information snapshot.

Client information is updated on connect and disconnect. Call queryClientsInfo() first when fresh latency data is required.

Parameters

  ppClientInfo | Output pointer that receives a borrowed local ClientInfo table, or nullptr when no clients are available. The returned pointer must not be deleted and remains valid until the next getClientsInfo() call or NetTCP::close().
  iCount | Output pointer that receives the number of clients in ppClientInfo [0,n].

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

## ◆ setTimeout()

eNetResult 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

  iMs | timeout in milliseconds. Minimum 500ms. Default 2000ms.

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

## ◆ getTimeout()

Sint32 CRM64Pro::NetTCP::getTimeout | ( |  | ) | const

Get the connection timeout.

Returns
  Timeout in milliseconds.

## ◆ setSimDelay()

eNetResult CRM64Pro::NetTCP::setSimDelay | ( | Sint32 | iMs | ) |

Simulate a connection delay.

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

Parameters

  iMs | simulated delay in milliseconds [0-2500]. Default 0.

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

## ◆ getSimDelay()

Sint32 CRM64Pro::NetTCP::getSimDelay | ( |  | ) | const

Get the simulated connection delay.

Returns
  Simulated delay in milliseconds [0-2500].

## ◆ createServer()

eNetResult CRM64Pro::NetTCP::createServer | ( | Uint16 | iPort,
|  | const string & | sPassword,
|  | bool | bDedicated )

Create a server.

Parameters

  iPort | the listening server port (1024 to 65535).
  sPassword | server password/passphrase. Maximum length is 64 characters.
  bDedicated | true for dedicated mode (call blocks until server closes), or false for threaded mode (call returns immediately).

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.

Note
  Only one server can be created.

## ◆ setCoreServerCallback()

eNetResult CRM64Pro::NetTCP::setCoreServerCallback | ( | Sint32(* | fnCallback )(void *pData, Sint32 iSize, void *pUser),
|  | void * | pUser = nullptr )

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

Parameters

  fnCallback | Callback function taking data pointer, size, and optional pUser. 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.
  pUser | Optional user pointer passed to fnCallback. Default nullptr.

Returns
  ::NR_OK on success, or a negative ::eNetResult on failure.