Skip to main content
Version: v3

NetFrames

Important Attention Reminder

Coding Style wiki


NetFrames is the unified entry point (Facade) of the NetFrame module. It manages multiple network connections as nodes (NetNode), where each node pairs its own transport implementation (INetProvider) with its own connection options (NetOption). It covers node registration, connecting, sending data, and closing, plus control over the updater that drives network polling.

NamespaceOxGFrame.NetFrame
Typepublic static class
SourceNetFrames.cs
using OxGFrame.NetFrame;

Attention Before calling any connection-related API, create a NetNode yourself and register it via AddNetNode. See the NetFrame Introduction for the full setup flow.

Quick Start

// Create a network node (built-in TCP provider; NetTipsExample is a custom INetTips implementation)
var netNode = new NetNode(new TcpNetProvider(), new NetTipsExample());
netNode.SetResponseBinaryHandler(recvData => Debug.Log($"Received {recvData.Length} bytes"));

// Register the node (use the default nnId = 0 for a single connection)
NetFrames.AddNetNode(netNode);

// Connect to the server
NetFrames.Connect(new TcpNetOption("127.0.0.1", 8888));

// Send binary data
NetFrames.Send(new byte[] { 0x01, 0x02 });

// Close the connection and remove the node
NetFrames.Close(0, removeNetNode: true);

General Rules

Multi-Node Management (nnId)

NetFrame organizes network connections in units of nodes (NetNode). Each node owns its own transport implementation (INetProvider), connection options (NetOption), and status tips (INetTips), and is managed by a unique nnId (node ID) — every facade method targets a node by its nnId.

Attention For most single-connection scenarios, simply use the default nnId = 0. If you need to connect to multiple servers at once (e.g., a Login Server and a Game Server), assign a separate nnId to each node.

Reminder A NetNode also supports heartbeat, receive-timeout, and reconnection callbacks (SetHeartBeatAction, SetOutReceiveAction, SetReconnectAction, etc.). See the NetFrame Introduction for the full setup flow.

Built-in Providers

Three INetProvider implementations are built in; pass the matching NetOption derived class when connecting. You can also implement INetProvider yourself to support other transport protocols.

ProviderUnderlying LibraryNetOptionString Sending
TcpNetProviderTelepathyTcpNetOptionNot supported
KcpNetProviderkcp2kKcpNetOptionNot supported
WebSocketNetProviderUnityWebSocketWebSocketNetOptionSupported

Attention TcpNetProvider and KcpNetProvider support binary sending only — calling the string overload of Send on them throws an exception.

Updater

NetManager uses an independent RTUpdater (Real-time Updater) to drive the polling logic of all nodes (data receiving, heartbeat, receive-timeout, and reconnection timing). The manager initializes automatically on the first call to any NetFrames API and starts the updater on the main thread.

Reminder RTUpdater is a real-time updater unaffected by Unity's Time.timeScale — network communication keeps running even while the game is paused.

Important When the updater is switched to a separate thread via StartUpdaterOnThread or ResetUpdaterOnThread, all network callbacks (such as the binary receive handler) fire on a non-main thread. If you need to touch Unity components, take care of thread safety and dispatch back to the main thread with UMT.


Node Management

Registering, retrieving, and removing nodes. A NetNode must be created yourself with new NetNode(INetProvider, INetTips) and then registered with the manager (see Multi-Node Management).

Method Overview

Initialization

MethodDescription
InitInstanceInitializes the NetManager singleton instance.

Node Registration & Access

MethodDescription
AddNetNodeRegisters a network node with the manager.
RemoveNetNodeDisposes and removes the given node.
GetNetNodeGets a registered network node.
CountGets the total number of registered nodes.

InitInstance

public static void InitInstance()

Description

Explicitly initializes the NetManager singleton instance. Initialization also creates the updater and starts it on the main thread. It is recommended to call this once during game startup so the manager is ready ahead of time.

Reminder Every NetFrames API initializes the manager automatically on its first call — this method only serves to initialize it in advance.


AddNetNode

public static void AddNetNode(NetNode netNode, int nnId = 0)

Parameters

ParameterTypeDescription
netNodeNetNodeThe network node instance to register.
nnIdintUnique identifier of the node.
Default: 0

Description

Registers a network node with the manager. Afterwards, the node can be connected, used for sending, and closed via its nnId.

Attention If the nnId already exists, the previous node is disposed first (closing its connection and releasing its resources), then replaced by the new one.

Example

public enum NNID
{
WebSocket = 0,
TCP = 1,
KCP = 2
}

// Register the WebSocket node
var wsNode = new NetNode(new WebSocketNetProvider(), new NetTipsExample());
NetFrames.AddNetNode(wsNode, (int)NNID.WebSocket);

// Register the TCP node
var tcpNode = new NetNode(new TcpNetProvider(), new NetTipsExample());
NetFrames.AddNetNode(tcpNode, (int)NNID.TCP);

RemoveNetNode

public static void RemoveNetNode(int nnId = 0)

Parameters

ParameterTypeDescription
nnIdintUnique identifier of the node.
Default: 0

Description

Removes the given node from the manager. The node is disposed before removal (its connection is closed and its callbacks and timers are released). Does nothing if the node is not found.


GetNetNode

public static NetNode GetNetNode(int nnId = 0)

Parameters

ParameterTypeDescription
nnIdintUnique identifier of the node.
Default: 0

Returns

NetNode — the registered node instance; null if not found.

Description

Gets a registered network node. Useful for advanced node configuration (heartbeat, receive-timeout, and reconnection callbacks) or for accessing the underlying provider via GetNetProvider<T>().

Example

// Check whether the node is registered
if (NetFrames.GetNetNode() == null)
{
// Not registered yet — create the node first
}

// Get the underlying provider and send through the KCP Unreliable channel
NetFrames.GetNetNode((int)NNID.KCP)
.GetNetProvider<KcpNetProvider>()
.SendBinary(kcp2k.KcpChannel.Unreliable, buffer);

Count

public static int Count()

Returns

int — the total number of currently registered network nodes.

Description

Gets the number of nodes registered with the manager.


Connection & Communication

Network operations — connecting, sending, and closing — performed on a specific node.

Method Overview

Connection

MethodDescription
ConnectOpens the connection of the given node.
IsConnectedChecks the connection state of the given node.

Sending & Closing

MethodDescription
SendSends binary or string data through the given node.
CloseCloses the connection of the given node.
CloseAllCloses the connections of all nodes.

Connect

public static void Connect(NetOption netOption, int nnId = 0)

Parameters

ParameterTypeDescription
netOptionNetOptionConnection options. Pass the derived class matching the node's provider (e.g., TcpNetOption, KcpNetOption, WebSocketNetOption).
nnIdintUnique identifier of the target node.
Default: 0

Description

Opens the connection of the given node. When the connection procedure starts, INetTips.OnConnecting and the node's connecting callback are triggered; once established, INetTips.OnConnected and the connected callback are triggered. An error is logged if the node is not found.

Attention
  • The type of netOption must match the node's provider — the implementation casts it back to obtain the connection parameters.
  • A node only starts the connection procedure while it is disconnected (DISCONNECTED) or reconnecting (RECONNECTING); calling this repeatedly does not create a second connection.

Example

// TCP connection (auto-reconnect 3 times after disconnection)
NetFrames.Connect(new TcpNetOption("127.0.0.1", 8888, autoReconnectCount: 3), (int)NNID.TCP);

// WebSocket connection
NetFrames.Connect(new WebSocketNetOption("ws://127.0.0.1:8080/ws"), (int)NNID.WebSocket);

IsConnected

public static bool IsConnected(int nnId = 0)

Parameters

ParameterTypeDescription
nnIdintUnique identifier of the target node.
Default: 0

Returns

booltrue if the node is connected; false if the node is not found or not connected.

Description

Checks the connection state of the given node's underlying provider.


Send

public static bool Send(byte[] buffer, int nnId = 0)
public static bool Send(string text, int nnId = 0)

Parameters

ParameterTypeDescription
bufferbyte[]Binary data to send.
textstringString data to send.
nnIdintUnique identifier of the target node.
Default: 0

Returns

booltrue if the data was successfully handed to the underlying provider; false if the node is not found or not connected.

Description

Sends data through the given node. The binary overload maps to the provider's SendBinary; the string overload maps to SendMessage.

Important The built-in TcpNetProvider and KcpNetProvider do not support string sending — calling the string overload throws an exception. Only WebSocketNetProvider supports it.

Example

// Send binary data
bool sent = NetFrames.Send(new byte[] { 0x01, 0x02, 0x03 });

// Send string data (WebSocket only)
NetFrames.Send("{\"cmd\":\"ping\"}", (int)NNID.WebSocket);

Close

public static void Close(int nnId = 0, bool removeNetNode = false)

Parameters

ParameterTypeDescription
nnIdintUnique identifier of the target node.
Default: 0
removeNetNodeboolWhether to also remove (dispose) the node from the manager after closing.
Default: false

Description

Closes the connection of the given node. A manual close is a forced close and never triggers auto-reconnection. If removeNetNode is false, the node stays registered and can be reconnected later via Connect. Does nothing if the node is not found.

Example

// Close the connection only (the node is kept and can reconnect)
NetFrames.Close();

// Close the connection and remove the node
NetFrames.Close((int)NNID.TCP, true);

CloseAll

public static void CloseAll(bool removeNetNode = false)

Parameters

ParameterTypeDescription
removeNetNodeboolWhether to also remove all nodes after closing.
Default: false

Description

Closes the connections of all registered nodes. The parameter behaves the same as in Close. Useful for a unified cleanup on logout or shutdown.


Updater Controls

Starting, stopping, resetting, and scaling the NetManager updater. See Updater for the concept and threading notes.

Method Overview

Start & Stop

MethodDescription
StartUpdaterStarts the updater on the main thread.
StartUpdaterOnThreadStarts the updater on a separate thread.
StopUpdaterStops the updater.
IsUpdaterRunningChecks whether the updater is running.

Reset & Time Scale

MethodDescription
ResetUpdaterResets and restarts the updater.
ResetUpdaterOnThreadResets and restarts the updater on a separate thread.
SetUpdaterTimeScaleSets the updater's time scale.

StartUpdater

public static void StartUpdater()

Description

Starts the updater on the main thread. The manager already starts it in main-thread mode during initialization, so this is normally only needed to restart after StopUpdater.


StartUpdaterOnThread

public static void StartUpdaterOnThread()

Description

Starts the updater on a separate thread — useful to avoid blocking the main thread or for more responsive polling.

Important In threaded mode, all network callbacks fire on a non-main thread. Take care of thread safety when touching Unity components (see Updater).


StopUpdater

public static void StopUpdater()

Description

Stops the updater. Polling of all nodes (data receiving, heartbeat, receive-timeout, and reconnection timing) is suspended until the updater is started again.


IsUpdaterRunning

public static bool IsUpdaterRunning()

Returns

booltrue if the updater is currently running.

Description

Checks whether the NetManager updater is currently running.


ResetUpdater

public static void ResetUpdater()
public static void ResetUpdater(bool useThreadedUpdater)

Parameters

ParameterTypeDescription
useThreadedUpdaterboolWhether to restart in threaded mode. true = separate thread; false = main thread. The parameterless overload is equivalent to passing false.

Description

Stops and destroys the current updater, then re-creates and restarts it in the given mode. Useful for switching the threading mode or resetting the updater state.


ResetUpdaterOnThread

public static void ResetUpdaterOnThread()

Description

Resets the updater and restarts it on a separate thread — equivalent to calling ResetUpdater(true).


SetUpdaterTimeScale

public static void SetUpdaterTimeScale(float timeScale)

Parameters

ParameterTypeDescription
timeScalefloatTime scale factor.

Description

Sets the time scale of the NetManager updater (RTUpdater.timeScale).