### Minimal Nalix Server Example Source: https://ppn-system.me/packages/nalix-network-hosting This example demonstrates the basic setup of a Nalix server using NetworkApplication.CreateBuilder(). It configures logging, a connection hub, network options, registers packet types and handlers, and adds a TCP binding. Use this as a starting point for building your Nalix servers. ```csharp using Microsoft.Extensions.Logging; using Nalix.Framework.DataFrames.SignalFrames; using Nalix.Logging; using Nalix.Network.Connections; using Nalix.Network.Hosting; using Nalix.Network.Options; using Nalix.Runtime.Dispatching; ILogger logger = NLogix.Host.Instance; var app = NetworkApplication.CreateBuilder() .ConfigureLogging(logger) .ConfigureConnectionHub(new ConnectionHub()) .Configure(options => { options.Port = 57206; }) .AddPacket() .AddHandlers() .AddTcp() .Build(); await app.RunAsync(cancellationToken); ``` ```csharp [PacketController("SampleHandlers")] public sealed class SampleHandlers { [PacketOpcode(0x1001)] public ValueTask Handle(PacketContext request) => ValueTask.FromResult(new Control { Type = ControlType.PONG }); } ``` ```csharp public sealed class SampleProtocol : Protocol { private readonly IPacketDispatch _dispatch; public SampleProtocol(IPacketDispatch dispatch) => _dispatch = dispatch; public override void ProcessMessage(object sender, IConnectEventArgs args) => _dispatch.HandlePacket(args.Lease, args.Connection); } ``` -------------------------------- ### Basic Usage Example Source: https://ppn-system.me/api/hosting/network-application Demonstrates the basic setup and running of a network application with TCP binding. ```APIDOC ## Basic Usage ### Description This example shows how to create and run a network application using the builder pattern, including configuring logging, connection hub, buffer pool, socket options, packet types, handlers, and a TCP binding. ### Code Example ```csharp var app = NetworkApplication.CreateBuilder() .ConfigureLogging(logger) .ConfigureConnectionHub(new ConnectionHub(logger: logger)) .ConfigureBufferPoolManager(new BufferPoolManager(logger)) .Configure(options => { options.Port = 57206; }) .AddPacket() .AddHandlers() .AddTcp() .Build(); await app.RunAsync(cancellationToken); ``` ``` -------------------------------- ### Default Configuration File Example Source: https://ppn-system.me/installation Example of a default.ini configuration file used by server setups and SDK examples. This file is automatically generated in the project's output directory. ```ini [NetworkSocketOptions] Port=57206 Backlog=512 [DispatchOptions] MaxPerConnectionQueue=4096 DropPolicy=DropNewest BlockTimeout=00:00:01 [TransportOptions] Address=127.0.0.1 Port=57206 ConnectTimeoutMillis=7000 MaxPacketSize=65536 ``` -------------------------------- ### Add Nalix Hosting Packages Source: https://ppn-system.me/installation Install the recommended Nalix packages for a hosted server setup. This includes hosting, pipeline, and logging functionalities. ```bash dotnet add package Nalix.Network.Hosting dotnet add package Nalix.Network.Pipeline dotnet add package Nalix.Logging ``` -------------------------------- ### Basic Usage Example Source: https://ppn-system.me/api/framework/runtime/instance-manager Demonstrates the fundamental steps for registering a service and resolving instances using the Instance Manager. ```APIDOC ## Basic Usage ### Description Illustrates how to register a service and resolve instances. ### Code Example ```csharp // Startup var logger = new MyLogger(); InstanceManager.Instance.Register(logger); // Shared logic (No allocation) var taskManager = InstanceManager.Instance.GetOrCreateInstance(); ILogger? sharedLogger = InstanceManager.Instance.GetExistingInstance(); ``` ### Request Body (Conceptual for Register) ```json { "instance": "An instance of a registered type" } ``` ### Response (Conceptual for GetExistingInstance) ```json { "instance": "The resolved service instance or null" } ``` ``` -------------------------------- ### Start Direct Transport Listener Source: https://ppn-system.me/guides/networking/tcp-patterns Sets up required dependencies in InstanceManager and then initializes and activates a SampleTcpListener with a custom protocol. ```csharp // Setup dependencies InstanceManager.Instance.Register(logger); InstanceManager.Instance.Register(new ConnectionHub()); InstanceManager.Instance.Register(new TaskManager()); // Initialize and Activate SampleTcpListener listener = new(57206, new SampleProtocol(dispatch, logger)); listener.Activate(); ``` -------------------------------- ### Basic Usage Example Source: https://ppn-system.me/api/sdk/options/request-options Demonstrates how to use RequestOptions for standard and customized asynchronous requests. ```APIDOC ## Basic Usage ### Standard Request ```csharp // Standard request var response = await client.RequestAsync(packet); ``` ### High-Reliability Request ```csharp // High-reliability request var opts = RequestOptions.Default .WithTimeout(3000) .WithRetry(2) .WithEncrypt(); var secureResponse = await client.RequestAsync(sensitivePacket, opts); ``` ### Request with Predicate ```csharp // Explicit predicate for correlated replies var matchingResponse = await client.RequestAsync( sensitivePacket, RequestOptions.Default.WithTimeout(2000), predicate: response => response.RequestId == sensitivePacket.RequestId); ``` ``` -------------------------------- ### Example Validation Pass for Nalix Server Source: https://ppn-system.me/guides/deployment/production-checklist This example demonstrates a validation pass before release, including retrieving network socket options, validating them, activating the listener, generating reports for listener, dispatcher, and connection hub, and finally deactivating the listener. Ensure all startup options validate and reports generate without crashing. ```csharp NetworkSocketOptions socket = ConfigurationManager.Instance.Get(); socket.Validate(); await listener.Activate(ct); Console.WriteLine(listener.GenerateReport()); Console.WriteLine(dispatch.GenerateReport()); Console.WriteLine(connectionHub.GenerateReport()); await listener.Deactivate(ct); ``` -------------------------------- ### Use Hosting Predicate for Modern UDP Setup Source: https://ppn-system.me/guides/networking/udp-security Configure UDP listeners using a hosting predicate with NetworkApplication.CreateBuilder for a more modern approach than subclassing. This example checks if the connection level is at least USER. ```csharp using var app = NetworkApplication.CreateBuilder() .AddUdp((conn, ep, data) => conn.Level >= PermissionLevel.USER) .Build(); ``` -------------------------------- ### Client Request/Response Example Source: https://ppn-system.me/guides/networking/minimal-server Demonstrates establishing a connection and performing a type-safe request/response operation using Nalix.SDK. Includes setting a timeout option. ```csharp using Contracts; using Nalix.SDK.Transport.Extensions; // 1. Establish connection await session.ConnectAsync(); // 2. Request/Response in one line Control response = await session.RequestAsync( new Control { Type = ControlType.PING }, options: RequestOptions.Default.WithTimeout(3_000) ); Console.WriteLine(response.Type); // PONG ``` -------------------------------- ### Add Nalix Manual Server Packages Source: https://ppn-system.me/installation Install Nalix packages for a server setup requiring manual wiring. This provides more control over the startup order. ```bash dotnet add package Nalix.Network dotnet add package Nalix.Runtime dotnet add package Nalix.Framework dotnet add package Nalix.Common dotnet add package Nalix.Logging ``` -------------------------------- ### Basic TcpSession Usage Source: https://ppn-system.me/api/sdk/tcp-session Example demonstrating how to initialize, connect, send, and request data using TcpSession. ```APIDOC ## Basic Usage ```csharp var options = ConfigurationManager.Instance.Get(); var catalog = InstanceManager.Instance.GetExistingInstance(); using var client = new TcpSession(options, catalog); client.OnConnected += (s, e) => Console.WriteLine("Connected!"); client.OnMessageReceived += (s, lease) => { using (lease) // Ensure lease return to pool { Console.WriteLine($"Received {lease.Length} bytes"); } }; await client.ConnectAsync(); await client.SendAsync(new LoginPacket { Username = "Ghost" }); var loginResponse = await client.RequestAsync( new LoginPacket { Username = "Ghost" }, RequestOptions.Default.WithTimeout(5_000)); ``` ``` -------------------------------- ### Basic Usage Examples Source: https://ppn-system.me/api/sdk/subscriptions Illustrates common use cases for SDK subscriptions, including strongly-typed handlers, strict handlers, and one-shot subscriptions with predicates. ```APIDOC ## Basic Usage Examples This section provides practical examples of how to use the SDK subscription methods. ### Strongly-Typed Handler **Description**: Example of subscribing to a `ChatPacket` type. The handler is invoked only when a `ChatPacket` is received, and it safely manages the buffer lease. ```csharp using var sub = client.On(chat => { Console.WriteLine($"[{chat.Sender}]: {chat.Message}"); }); ``` ### Strict Typed Handler **Description**: Example using `OnExact` to subscribe to `ChatPacket`. This will log any non-`ChatPacket` types received without stopping the receive loop. ```csharp using var sub = client.OnExact(chat => { Console.WriteLine($"[{chat.Sender}]: {chat.Message}"); }); ``` ### One-Shot with Predicate **Description**: Example of subscribing to a `Control` packet that should only be processed if it's a `PONG` type. The subscription automatically unsubscribes after the first matching packet. ```csharp using var once = client.OnOnce( predicate: c => c.Type == ControlType.PONG, handler: pong => Console.WriteLine("Received PONG!") ); ``` ### Composite Subscriptions **Description**: Demonstrates how to group multiple subscriptions using `CompositeSubscription`. This is useful for managing the lifecycle of related event listeners, ensuring they are all disposed together. ```csharp var group = new CompositeSubscription(); group.Add(client.On(p => UpdatePos(p))); group.Add(client.On(s => UpdateStats(s))); // Later, or in Dispose(): group.Dispose(); // Unsubscribes all ``` ``` -------------------------------- ### Practical Example: Sending a Throttle Directive Source: https://ppn-system.me/api/network/connection/connection-extensions This example demonstrates how to use the SendAsync extension method to send a throttle directive with specific options. Ensure ControlType, ProtocolReason, and ProtocolAdvice are correctly set for your use case. ```csharp await connection.SendAsync( controlType: ControlType.THROTTLE, reason: ProtocolReason.RATE_LIMITED, action: ProtocolAdvice.RETRY, options: new ControlDirectiveOptions( Flags: ControlFlags.NONE, SequenceId: 42)); ``` -------------------------------- ### Get and Change Configuration Source Source: https://ppn-system.me/api/framework/runtime/configuration Use Get() to resolve configuration instances. Change the active configuration source at runtime using SetConfigFilePath, optionally enabling auto-reloading. ```csharp var network = ConfigurationManager.Instance.Get(); ConfigurationManager.Instance.SetConfigFilePath("prod.ini", autoReload: true); ``` -------------------------------- ### Basic Usage Example Source: https://ppn-system.me/api/framework/packets/reader-writer-and-header-extensions Demonstrates the basic usage of DataWriterExtensions, DataReaderExtensions, and HeaderExtensions for packet serialization and deserialization. ```APIDOC ## Basic usage ```csharp DataWriter writer = new(); writer.Write((ushort)opcode); writer.WriteEnum(priority); writer.Write(payload); DataReader reader = new(writer.WrittenSpan); ushort decodedOpcode = reader.ReadUInt16(); PacketPriority decodedPriority = reader.ReadEnumByte(); ushort headerOpcode = writer.WrittenSpan.ReadOpCodeLE(); ``` ``` -------------------------------- ### TCP Session Request Example Source: https://ppn-system.me/api/sdk Demonstrates configuring transport options, creating a TCP session, connecting, performing a handshake, and making a request with custom timeout and retry options. ```csharp TransportOptions options = new(); IPacketRegistry catalog = /* resolve registry */; using TcpSession session = new(options, catalog); await session.ConnectAsync(); await session.HandshakeAsync(); MyResponse response = await session.RequestAsync( new MyRequest(), RequestOptions.Default.WithTimeout(3_000).WithRetry(1)); ``` -------------------------------- ### Typical NLogix Integration with Logging Targets Source: https://ppn-system.me/api/logging/targets Sets up NLogix with minimum logging level and registers both BatchConsoleLogTarget and BatchFileLogTarget. This example demonstrates how to configure multiple logging sinks for an application. ```csharp using Microsoft.Extensions.Logging; using Nalix.Logging; using Nalix.Logging.Options; using Nalix.Logging.Sinks; var logger = new NLogix(cfg => { cfg.SetMinimumLevel(LogLevel.Debug) .RegisterTarget(new BatchConsoleLogTarget(options => { options.BatchSize = 64; options.EnableColors = true; })) .RegisterTarget(new BatchFileLogTarget(options => { options.LogFileName = "server.log"; options.UsePerProcessSuffix = true; })); }); ``` -------------------------------- ### Configure Server Certificate Path Source: https://ppn-system.me/quickstart Example of configuring the server to use a specific private certificate file during the build process. This is necessary if the certificate is not in the default location. ```csharp using var app = NetworkApplication.CreateBuilder() .ConfigureCertificate("./identity/certificate.private") // Add packets, handlers, and listeners here. .Build(); ``` -------------------------------- ### Securing a Packet with Attributes Source: https://ppn-system.me/api/runtime/middleware/permission-middleware This example demonstrates how to secure a packet by applying PacketOpcode and PacketPermission attributes. This is necessary for handlers/packets that enter a pipeline containing PermissionMiddleware. ```csharp [PacketOpcode(0x2001)] [PacketPermission(PermissionLevel.SYSTEM_ADMINISTRATOR)] public sealed class AdminCommandPacket : IPacket { // packet members } ``` -------------------------------- ### Basic IThreadDispatcher Usage Example Source: https://ppn-system.me/api/sdk/thread-dispatching Demonstrates how to use IThreadDispatcher to post an action to the main thread from a background thread. Ensure dispatcher is obtained via GetPlatformDispatcher(). ```csharp IThreadDispatcher dispatcher = GetPlatformDispatcher(); client.OnMessageReceived += (s, lease) => { // We are on a background thread here dispatcher.Post(() => { // Now safely on the Main Thread myLabel.Text = "Updated!"; }); }; ``` -------------------------------- ### Object Pool Configuration Example Source: https://ppn-system.me/api/framework/memory/object-pooling Configure advanced diagnostics and settings for the Object Pool system, such as enabling diagnostics, capturing stack traces, and setting thresholds for suspicious objects. ```ini [ObjectPool] EnableDiagnostics = true CaptureStackTraces = true EnableLeakDetection = true SuspiciousThresholdSeconds = 30 ``` -------------------------------- ### LZ4 Encode and Decode Example Source: https://ppn-system.me/api/framework/memory/lz4 Demonstrates encoding a span of bytes into a compressed buffer lease and then decoding it back. Ensure the buffer lease is disposed after use. ```csharp ReadOnlySpan input = payload; LZ4Codec.Encode(input, out BufferLease compressed, out int written); using (compressed) { LZ4Codec.Decode(compressed.Span, out BufferLease? restored, out int restoredBytes); using (restored) { Console.WriteLine(restoredBytes); } } ``` -------------------------------- ### Setup Server Project with Nalix Hosting Source: https://ppn-system.me/guides/getting-started/project-setup Creates a console application for the server, references the contracts project, and adds the Nalix network hosting package. This is the entry point for server-side logic. ```bash dotnet new console -n MyProject.Server dotnet add MyProject.Server reference MyProject.Contracts dotnet add MyProject.Server package Nalix.Network.Hosting --version 12.0.7 ``` -------------------------------- ### Basic Instance Manager Usage Source: https://ppn-system.me/api/framework/runtime/instance-manager Demonstrates registering a service and resolving it using InstanceManager. Use GetOrCreateInstance for singleton-like behavior and GetExistingInstance for direct retrieval. ```csharp // Startup var logger = new MyLogger(); InstanceManager.Instance.Register(logger); // Shared logic (No allocation) var taskManager = InstanceManager.Instance.GetOrCreateInstance(); ILogger? sharedLogger = InstanceManager.Instance.GetExistingInstance(); ``` -------------------------------- ### Custom Protocol Implementation Example Source: https://ppn-system.me/api/network/protocol Example of how to create a custom protocol by inheriting from the abstract Protocol class. You must implement the ProcessMessage method to handle payload semantics. ```csharp public class MyProtocol : Protocol { public override void ProcessMessage(object? sender, IConnectEventArgs args) { // 1. Read packet data from args.Lease (already decrypted/decompressed) // 2. Perform business routing (e.g., call a Dispatcher) // 3. The lease is disposed automatically after this method returns } } ``` -------------------------------- ### Setup Client Project with Nalix SDK Source: https://ppn-system.me/guides/getting-started/project-setup Creates a console application for the client and adds the Nalix SDK package, referencing the shared contracts project. This is the entry point for client-side integration. ```bash dotnet new console -n MyProject.Client dotnet add MyProject.Client reference MyProject.Contracts dotnet add MyProject.Client package Nalix.SDK --version 12.0.7 ``` -------------------------------- ### Get Current UTC Time and Monotonic Ticks Source: https://ppn-system.me/api/framework/runtime/clock Use `NowUtc()` to get the current Coordinated Universal Time and `MonoTicksNow()` for monotonic time. `MonoTicksToMilliseconds` converts these ticks to milliseconds. ```csharp DateTime now = Clock.NowUtc(); long mono = Clock.MonoTicksNow(); double ms = Clock.MonoTicksToMilliseconds(mono); ``` -------------------------------- ### Create Project Structure with .NET CLI Source: https://ppn-system.me/quickstart Sets up a solution with separate projects for shared contracts, server host, and client application using the .NET CLI. ```bash mkdir NalixPingPong && cd NalixPingPong dotnet new sln # 1. Shared Contracts dotnet new classlib -n Contracts dotnet add Contracts package Nalix.Common # 2. Server Host dotnet new console -n Server dotnet add Server reference Contracts dotnet add Server package Nalix.Network.Hosting # 3. Client App dotnet new console -n Client dotnet add Client reference Contracts dotnet add Client package Nalix.SDK dotnet sln add Contracts Server Client ``` -------------------------------- ### Basic Logging with NLogixFx Extensions Source: https://ppn-system.me/api/logging/extensions Demonstrates how to use Info, Warn, and Error extensions for logging messages and exceptions. Ensure Nalix.Logging.Extensions is imported. ```csharp using Nalix.Logging.Extensions; "listener started".Info(typeof(SampleProtocol)); "high latency detected".Warn(typeof(SampleProtocol)); exception.Error(typeof(SampleProtocol), "dispatch-failed"); ``` -------------------------------- ### Basic UdpSession Usage Source: https://ppn-system.me/api/sdk/udp-session Example demonstrating the basic usage of the UdpSession for sending datagrams. ```APIDOC ## Basic Usage ```csharp var client = new UdpSession(options, catalog); // Essential: must match the session identifier assigned during TCP login client.SessionToken = mySessionSnowflake; client.OnMessageReceived += (s, lease) => { using (lease) { // Handle low-latency update } }; await client.ConnectAsync(); await client.SendAsync(new PlayerInputPacket { Velocity = 1.0f }); ``` ``` -------------------------------- ### Handle No Reply Source: https://ppn-system.me/api/runtime/routing/handler-results Example of a handler that does not send a reply, returning ValueTask.CompletedTask. Useful for commands or notifications. ```csharp [PacketOpcode(0x1003)] public static ValueTask HandleNoReply(IPacketContext context) => ValueTask.CompletedTask; ``` -------------------------------- ### Get Formatter Instance Source: https://ppn-system.me/api/framework/packets/serialization Retrieve a formatter instance for a specific model type using FormatterProvider.Get(). ```csharp IFormatter formatter = FormatterProvider.Get(); ``` -------------------------------- ### Run Nalix SDK Tools from Source Source: https://ppn-system.me/guides/tools/sdk-tools Navigate to the tool directory and use the .NET CLI to run the SDK Tools application. ```bash cd tools/Nalix.SDK.Tools dotnet run ``` -------------------------------- ### Typical Directories Usage Source: https://ppn-system.me/api/framework/environment/directories Demonstrates common usage patterns for accessing configuration and log file paths, and creating subdirectories within the data directory. ```csharp // Get paths string configFile = Directories.GetConfigFilePath("default.ini"); string logFile = Directories.GetLogFilePath("server.log"); // Create structure string imports = Directories.CreateSubdirectory(Directories.DataDirectory, "imports"); ``` -------------------------------- ### Protocol Implementation Contract Source: https://ppn-system.me/api/network/protocol Provides an example of how to implement a custom protocol by inheriting from the abstract `Protocol` class. ```APIDOC ## Protocol Implementation Contract ### Description This section demonstrates how to create a custom protocol by inheriting from the abstract `Protocol` class and implementing the required `ProcessMessage` method. ### Method `MyProtocol` (Derived Class) ### Endpoint N/A (Class Implementation) ### Parameters N/A ### Request Body N/A ### Response N/A ### Code Example ```csharp public class MyProtocol : Protocol { public override void ProcessMessage(object? sender, IConnectEventArgs args) { // 1. Read packet data from args.Lease (already decrypted/decompressed) // 2. Perform business routing (e.g., call a Dispatcher) // 3. The lease is disposed automatically after this method returns } } ``` ``` -------------------------------- ### ScheduleRecurring API Source: https://ppn-system.me/api/framework/runtime/task-manager Starts a recurring background task. Allows monitoring of its execution status and failure counts. ```APIDOC ## POST /api/tasks/schedule-recurring ### Description Starts a background loop (recurring task). You can monitor the `LastRunUtc` and `ConsecutiveFailures` through the returned `IRecurringHandle`. ### Method POST ### Endpoint /api/tasks/schedule-recurring ### Parameters #### Request Body - **recurringTaskDetails** (object) - Required - Details of the recurring task. - **interval** (duration) - Required - How often the task should run (e.g., '1h', '5m'). - **nonReentrant** (boolean) - Optional - If true, prevents the task from running concurrently if a previous instance is still active. - **priority** (integer) - Optional - Priority of the recurring task. - **group** (string) - Optional - The group the recurring task belongs to. ### Request Example ```json { "recurringTaskDetails": { "interval": "1h", "nonReentrant": true, "group": "cache-cleanup" } } ``` ### Response #### Success Response (200) - **recurringHandle** (object) - An object representing the scheduled recurring task. - **id** (string) - Unique identifier for the recurring task. - **lastRunUtc** (datetime) - The timestamp of the last execution. - **consecutiveFailures** (integer) - The number of consecutive times the task has failed. #### Response Example ```json { "recurringHandle": { "id": "recurring-abcde", "lastRunUtc": "2023-10-27T10:00:00Z", "consecutiveFailures": 0 } } ``` ``` -------------------------------- ### Example Protocol Flow Source: https://ppn-system.me/api/common/connection-contracts Demonstrates a typical flow for accepting a connection and processing a message using IConnection and IProtocol. Ensure proper handling of connection lifecycle and message processing. ```csharp IConnection connection = hub.GetConnection(connectionId); IProtocol protocol = new SampleProtocol(); protocol.OnAccept(connection, ct); protocol.ProcessMessage(sender, args); ``` -------------------------------- ### Custom Nalix Logger Setup Source: https://ppn-system.me/api/logging Shows how to create a custom NLogix logger with specific configurations, including setting the minimum log level and registering custom log targets like console and file sinks. ```csharp using Microsoft.Extensions.Logging; using Nalix.Logging; using Nalix.Logging.Sinks; NLogix logger = new(cfg => { cfg.SetMinimumLevel(LogLevel.Debug) .RegisterTarget(new BatchConsoleLogTarget()) .RegisterTarget(new BatchFileLogTarget()); }); ``` -------------------------------- ### Handle Login Response Source: https://ppn-system.me/api/runtime/routing/handler-results Example of a synchronous handler returning a LoginResponse packet. Use for simple request/response patterns. ```csharp using System.Threading.Tasks; using Nalix.Common.Networking.Packets; [PacketOpcode(0x1001)] public static LoginResponse Handle(LoginRequest request) => new(); ``` -------------------------------- ### Load Compression Options Source: https://ppn-system.me/api/network/options/compression-options Loads CompressionOptions during server startup to materialize the configuration template into server.ini. ```csharp _ = ConfigurationManager.Instance.Get(); ``` -------------------------------- ### Load and Validate Network Options Source: https://ppn-system.me/guides/getting-started/server-blueprint Load and validate network options before starting the runtime. This follows a fail-fast approach. ```csharp var socket = ConfigurationManager.Instance.Get(); socket.Validate(); var dispatchOptions = ConfigurationManager.Instance.Get(); dispatchOptions.Validate(); var connectionLimits = ConfigurationManager.Instance.Get(); connectionLimits.Validate(); ``` -------------------------------- ### Handle Async Login Response Source: https://ppn-system.me/api/runtime/routing/handler-results Example of an asynchronous handler returning a LoginResponse packet. Use when operations require awaiting. ```csharp [PacketOpcode(0x1002)] public static async Task HandleAsync(LoginRequest request) { await Task.Yield(); return new LoginResponse(); } ``` -------------------------------- ### Run Packet Serialization Inspector Project Source: https://ppn-system.me/guides/tools/packet-visualizer Navigate to the tool's directory and run the .NET project to launch the inspector. ```bash dotnet run ``` -------------------------------- ### Create Project Assemblies Source: https://ppn-system.me/guides/deployment/production-example Sets up the basic project structure for a Nalix application, including contracts, server, and client assemblies. ```bash dotnet new classlib -n MyNet.Contracts dotnet new console -n MyNet.Server dotnet new console -n MyNet.Client ``` -------------------------------- ### Initialize Session Store Options Source: https://ppn-system.me/api/network/options/session-store-options Materializes SessionStoreOptions during server startup. Ensures server.ini contains retention and persistence policies. ```csharp _ = ConfigurationManager.Instance.Get(); ``` -------------------------------- ### Define a Serializable Packet for Communication Source: https://ppn-system.me/guides/getting-started/project-setup Example of a packet class annotated with `[SerializePackable]` and `[SerializeOrder]` for explicit field layout. Defines constants for OpCodes. ```csharp [SerializePackable] public sealed class JoinRequest : PacketBase { public const ushort OpCodeValue = 0x3001; public string Username { get; set; } = string.Empty; public JoinRequest() => OpCode = OpCodeValue; } ``` -------------------------------- ### Load ConnectionLimitOptions Source: https://ppn-system.me/api/network/options/connection-limit-options Loads ConnectionLimitOptions during server startup. The returned instance is validated by runtime consumers. ```csharp _ = ConfigurationManager.Instance.Get(); ``` -------------------------------- ### Register Custom Metadata Provider Source: https://ppn-system.me/api/runtime/routing/packet-metadata Example of creating and registering a custom IPacketMetadataProvider. This provider sets a specific timeout for methods ending with 'Critical'. ```csharp public sealed class MyMetadataProvider : IPacketMetadataProvider { public void Populate(MethodInfo method, PacketMetadataBuilder builder) { if (method.Name.EndsWith("Critical", StringComparison.Ordinal)) { builder.Timeout = new PacketTimeoutAttribute(2000); } } } PacketMetadataProviders.Register(new MyMetadataProvider()); ``` -------------------------------- ### Start TCP Listener Source: https://ppn-system.me/guides/networking/minimal-server Initialize and activate a TcpListenerBase with a specific port, protocol, and connection hub. This component listens for incoming TCP connections. ```csharp public sealed class SampleTcpListener : TcpListenerBase { public SampleTcpListener(ushort port, IProtocol protocol, IConnectionHub hub) : base(port, protocol, hub) { } } IConnectionHub hub = new ConnectionHub(); SampleTcpListener listener = new(57206, new SampleProtocol(dispatch), hub); listener.Activate(); ```