NetSquare.Client 1.0.7

dotnet add package NetSquare.Client --version 1.0.7
                    
NuGet\Install-Package NetSquare.Client -Version 1.0.7
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NetSquare.Client" Version="1.0.7" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NetSquare.Client" Version="1.0.7" />
                    
Directory.Packages.props
<PackageReference Include="NetSquare.Client" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NetSquare.Client --version 1.0.7
                    
#r "nuget: NetSquare.Client, 1.0.7"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NetSquare.Client@1.0.7
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NetSquare.Client&version=1.0.7
                    
Install as a Cake Addin
#tool nuget:?package=NetSquare.Client&version=1.0.7
                    
Install as a Cake Tool

NetSquare.Client

NetSquare.Client is the client-side package for NetSquare. It provides a TCP client with optional UDP messaging, request/reply callbacks, dispatcher-based message routing, server time synchronization, and world synchronization helpers.

The package targets .NET Standard 2.0, .NET 8, and .NET Framework 4.8. It includes NetSquareClient.dll and depends on NetSquare.Core.

Installation

NuGet\Install-Package NetSquare.Client -Version 1.0.7

or:

dotnet add package NetSquare.Client --version 1.0.7

Basic Client

using System;
using NetSquare.Client;
using NetSquare.Core;

public enum GameMessage : ushort
{
    Chat = 1,
    Ping = 2,
    Welcome = 3
}

public static class Program
{
    public static void Main()
    {
        NetSquareClient client = new NetSquareClient(autoBindNetsquareActions: false);

        client.OnConnected += clientID =>
        {
            Console.WriteLine("Connected as " + clientID);
            client.SendMessage(new NetworkMessage(GameMessage.Chat).Set("Hello server"));
        };

        client.OnDisconected += () => Console.WriteLine("Disconnected");
        client.OnConnectionFail += () => Console.WriteLine("Connection failed");
        client.OnException += ex => Console.WriteLine(ex);

        client.Dispatcher.AddHeadAction(GameMessage.Welcome, "Welcome", message =>
        {
            string text = message.Serializer.GetString();
            uint assignedClientID = message.Serializer.GetUInt();
            Console.WriteLine(text + " - assigned ID: " + assignedClientID);
        });

        client.Dispatcher.AddHeadAction(GameMessage.Chat, "Chat", message =>
        {
            uint senderID = message.Serializer.GetUInt();
            string text = message.Serializer.GetString();
            Console.WriteLine(senderID + ": " + text);
        });

        client.Connect("127.0.0.1", 5555, NetSquareProtocoleType.TCP_AND_UDP);

        Console.WriteLine("Press Enter to disconnect.");
        Console.ReadLine();
        client.Disconnect();
    }
}

Sending Messages

Use NetworkMessage to write values in the order the receiver will read them.

client.SendMessage(
    new NetworkMessage(GameMessage.Chat)
        .Set("hello")
        .Set(123)
        .Set(true));

Read values from message.Serializer in the same order:

string text = message.Serializer.GetString();
int number = message.Serializer.GetInt();
bool enabled = message.Serializer.GetBool();

Supported helpers include numeric primitives, strings, chars, booleans, byte arrays, numeric arrays, INetSquareSerializable objects, lists, and dictionaries.

Request and Reply

Use the callback overload of SendMessage when the server should answer a specific request.

client.SendMessage(new NetworkMessage(GameMessage.Ping).Set("ping"), reply =>
{
    string response = reply.Serializer.GetString();
    Console.WriteLine("Server replied: " + response);
});

The server must call server.Reply(originalMessage, replyMessage) for this callback to run.

TCP and UDP

TCP is reliable and ordered:

client.SendMessage(new NetworkMessage(GameMessage.Chat).Set("reliable payload"));

UDP is faster but unreliable:

client.SendMessageUDP(new NetworkMessage(GameMessage.Chat).Set("unreliable payload"));

Connect with NetSquareProtocoleType.TCP_AND_UDP to enable both transports:

client.Connect("127.0.0.1", 5555, NetSquareProtocoleType.TCP_AND_UDP);

If world synchronization should use UDP, keep synchronizeUsingUDP enabled:

client.Connect("127.0.0.1", 5555, NetSquareProtocoleType.TCP_AND_UDP, synchronizeUsingUDP: true);

Dispatcher

Register callbacks manually:

client.Dispatcher.AddHeadAction(GameMessage.Chat, "Chat", message =>
{
    string text = message.Serializer.GetString();
});

Or auto-bind public static methods with NetSquareActionAttribute:

using NetSquare.Core;

public static class ClientHandlers
{
    [NetSquareAction(GameMessage.Chat)]
    public static void OnChat(NetworkMessage message)
    {
        string text = message.Serializer.GetString();
    }
}

Enable auto-binding by constructing the client with autoBindNetsquareActions: true.

Main Thread Dispatching

Callbacks can run from NetSquare worker threads. UI frameworks and Unity usually require work to run on the main thread. Use SetMainThreadCallback to marshal dispatch callbacks.

using System;
using System.Collections.Concurrent;

ConcurrentQueue<Action> mainThreadQueue = new ConcurrentQueue<Action>();

client.Dispatcher.SetMainThreadCallback((action, message) =>
{
    mainThreadQueue.Enqueue(() => action(message));
});

// Run this from your UI loop or Unity Update method.
while (mainThreadQueue.TryDequeue(out Action callback))
{
    callback();
}

Server Time Synchronization

SyncTime estimates server time from a monotonic client clock and round-trip delay. Use an unscaled Stopwatch time source so local clock changes do not affect synchronization.

using System.Diagnostics;

Stopwatch stopwatch = Stopwatch.StartNew();

client.SyncTime(
    getClientTime: () => (float)stopwatch.Elapsed.TotalSeconds,
    precision: 5,
    timeBetweenSyncs: 1000,
    onServerTimeGet: serverTime => Console.WriteLine("Server time: " + serverTime),
    onLog: Console.WriteLine);

float synchronizedTime = client.GetServerTime((float)stopwatch.Elapsed.TotalSeconds);

SmoothServerTimeOffset is enabled by default so offset changes are applied gradually. TimeSynchronizationRequestTimeoutMs bounds each request, and TimeSynchronizationMaxAttempts can cap retries when packets or replies are lost.

For long sessions, keep time synchronized automatically with a low-rate background refresh:

client.StartAutoSyncTime(
    getClientTime: () => (float)stopwatch.Elapsed.TotalSeconds,
    precision: 3,
    timeBetweenSyncs: 50,
    intervalMs: 30000);

bool fresh = client.IsServerTimeSynchronizationFresh(45000);

client.StopAutoSyncTime();

World Synchronization

Join a server world and send transform frames:

client.WorldsManager.TryJoinWorld(1, new NetsquareTransformFrame(0, 0, 0), joined =>
{
    Console.WriteLine("Joined world: " + joined);
});

client.WorldsManager.OnClientJoinWorld += (clientID, transform, message) =>
{
    Console.WriteLine("Client joined world: " + clientID + " at " + transform);
};

client.WorldsManager.OnClientLeaveWorld += clientID =>
{
    Console.WriteLine("Client left world: " + clientID);
};

client.WorldsManager.OnReceiveSynchFrames += (clientID, frames) =>
{
    foreach (INetSquareSynchFrame frame in frames)
        Console.WriteLine("Frame from " + clientID + ": " + frame.SynchFrameType);
};

client.WorldsManager.SendSynchFrame(
    new NetsquareTransformFrame(_x: 10, _y: 0, _z: 5, _time: 1.25f));

You can queue frames and send them as a batch:

client.WorldsManager.StoreSynchFrame(new NetsquareTransformFrame(_x: 1, _y: 0, _z: 0));
client.WorldsManager.StoreSynchFrame(new NetsquareTransformFrame(_x: 2, _y: 0, _z: 0));
client.WorldsManager.SendFrames();

Useful Client Properties

  • ClientID: current server-assigned ID.
  • IsConnected: whether the TCP socket is connected.
  • NbSendingMessages: pending outgoing messages.
  • NbProcessingMessages: queued incoming messages waiting for dispatch.
  • ServerTimeOffset: current estimated server time offset.
  • WorldsManager: world membership and synchronization API.

License

MIT

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 is compatible.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.7 44 5/30/2026
1.0.5 110 5/10/2026
1.0.4 95 5/9/2026
1.0.3 98 5/9/2026
1.0.2 96 5/8/2026
1.0.1 476 4/24/2022
1.0.0 367 4/24/2022

Adds robust server time synchronization with timeout-bounded samples, RTT filtering, and automatic low-rate refresh.