### Run Telepathy Server Source: https://github.com/mirrornetworking/telepathy/blob/master/LoadTest/README.md Starts the Telepathy server. Ensure you are in the 'bin/Debug' directory. ```bash cd bin/Debug mono LoadTest.exe server 1337 ``` -------------------------------- ### Server Creation and Configuration Source: https://context7.com/mirrornetworking/telepathy/llms.txt Instantiate a Server with a maximum message size and configure optional socket properties before starting the server and processing events. ```APIDOC ## Server(int MaxMessageSize) ### Description Create and configure a server instance. The `MaxMessageSize` parameter prevents allocation attacks and is shared across all connections. Optional properties like `NoDelay`, `SendTimeout`, `ReceiveTimeout`, `SendQueueLimit`, and `ReceiveQueueLimit` can be configured before calling `Start()`. ### Method `Server(int MaxMessageSize)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using System; using Telepathy; // Create server allowing messages up to 16 KB Server server = new Server(16 * 1024); // Configure socket options (optional, these are the defaults) server.NoDelay = true; // disable Nagle algorithm for lower latency server.SendTimeout = 5000; // 5-second send timeout (ms) server.ReceiveTimeout = 0; // disabled by default server.SendQueueLimit = 10000; // auto-disconnect if send backlog exceeds this server.ReceiveQueueLimit = 10000; // Hook events — connectionId identifies each client uniquely server.OnConnected = (connectionId, address) => Console.WriteLine($"[+] Client {connectionId} connected from {address}"); server.OnData = (connectionId, message) => { // message ArraySegment is only valid until this callback returns (allocation-free) string text = System.Text.Encoding.UTF8.GetString(message.Array, message.Offset, message.Count); Console.WriteLine($"[>] #{connectionId}: {text}"); // Echo the message back to the same client server.Send(connectionId, message); }; server.OnDisconnected = (connectionId) => Console.WriteLine($"[-] Client {connectionId} disconnected"); // Start listening on port 1337 bool started = server.Start(1337); Console.WriteLine(started ? "Server started" : "Server already active"); // Game/application loop — call Tick every frame to process messages // processLimit prevents spending too long here if messages pile up while (server.Active) { int remaining = server.Tick(100); // process up to 100 messages per frame // remaining > 0 means there are more messages; call Tick again if needed System.Threading.Thread.Sleep(1000 / 60); // ~60 fps } // Shutdown server.Stop(); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Run Telepathy Server and Clients Source: https://github.com/mirrornetworking/telepathy/blob/master/LoadTest/README.md Starts both the Telepathy server and clients. Ensure you are in the 'bin/Debug' directory. ```bash cd bin/Debug mono LoadTest.exe ``` -------------------------------- ### Connect to a server using Client.Connect Source: https://context7.com/mirrornetworking/telepathy/llms.txt Initiate a connection to a server via `Client.Connect`. This method starts a background thread for the connection attempt and supports hostnames. Connection status is reported via `Connected` or `Disconnected` events. ```csharp // Reconnect pattern: reconnect on disconnect client.OnDisconnected = () => { Console.WriteLine("Lost connection. Reconnecting in 2s..."); System.Threading.Thread.Sleep(2000); client.Connect("game.example.com", 1337); // hostname resolved automatically }; client.Connect("game.example.com", 1337); ``` -------------------------------- ### Telepathy Server Setup and Usage Source: https://github.com/mirrornetworking/telepathy/blob/master/README.md Demonstrates how to create, start, manage, and send messages with a Telepathy server. Ensure to call Tick in your update loop and limit the parameter to prevent deadlocks. The message ArraySegment is only valid until returning. ```csharp // create server & hook up events // note that the message ArraySegment is only valid until returning (allocation free) Telepathy.Server server = new Telepathy.Server(1024); server.OnConnected = (connectionId) => Console.WriteLine(connectionId + " Connected"); server.OnData = (connectionId, message) => Console.WriteLine(connectionId + " Data: " + BitConverter.ToString(message.Array, message.Offset, message.Count)); server.OnDisconnected = (connectionId) => Console.WriteLine(connectionId + " Disconnected"); // start server.Start(1337); // tick to process incoming messages (do this in your update loop) // => limit parameter to avoid deadlocks! server.Tick(100); // send a message to client with connectionId = 0 (first one) byte[] message = new byte[]{0x42, 0x13, 0x37}; server.Send(0, new ArraySegment(message)); // stop the server when you don't need it anymore server.Stop(); ``` -------------------------------- ### Run Telepathy Clients Source: https://github.com/mirrornetworking/telepathy/blob/master/LoadTest/README.md Starts multiple Telepathy clients connecting to a specified server. Ensure you are in the 'bin/Debug' directory. ```bash cd bin/Debug mono LoadTest.exe client 127.0.0.1 1337 1000 ``` -------------------------------- ### Client.Connect(string ip, int port) Source: https://context7.com/mirrornetworking/telepathy/llms.txt Starts a background thread that resolves the hostname and establishes a TCP connection. Supports IPv4, IPv6, and hostnames transparently. If already connecting or connected, the call is ignored. A Connected or Disconnected event will be dispatched through Tick() once the attempt completes. ```APIDOC ## Client.Connect(string ip, int port) ### Description Starts a background thread that resolves the hostname and establishes a TCP connection. Supports IPv4, IPv6, and hostnames transparently. If already connecting or connected, the call is ignored. A `Connected` or `Disconnected` event will be dispatched through `Tick()` once the attempt completes. ### Method `Client.Connect(string ip, int port)` ### Parameters #### Path Parameters - **ip** (string) - Required - The IP address or hostname of the server to connect to. - **port** (int) - Required - The port number of the server. ### Request Example ```csharp // Reconnect pattern: reconnect on disconnect client.OnDisconnected = () => { Console.WriteLine("Lost connection. Reconnecting in 2s..."); System.Threading.Thread.Sleep(2000); client.Connect("game.example.com", 1337); // hostname resolved automatically }; client.Connect("game.example.com", 1337); ``` ``` -------------------------------- ### Telepathy Client Setup and Usage Source: https://github.com/mirrornetworking/telepathy/blob/master/README.md Illustrates how to initialize, connect, send messages, and disconnect a Telepathy client. The message ArraySegment is only valid until returning. Remember to call Tick in your update loop with a limit to avoid deadlocks. ```csharp // create client & hook up events // note that the message ArraySegment is only valid until returning (allocation free) Telepathy.Client client = new Telepathy.Client(1024); client.OnConnected = () => Console.WriteLine("Client Connected"); client.OnData = (message) => Console.WriteLine("Client Data: " + BitConverter.ToString(message.Array, message.Offset, message.Count)); client.OnDisconnected = () => Console.WriteLine("Client Disconnected"); // connect client.Connect("localhost", 1337); // tick to process incoming messages (do this in your update loop) // => limit parameter to avoid deadlocks! client.Tick(100); // send a message to server byte[] message = new byte[]{0xFF}; client.Send(new ArraySegment(message)); // disconnect from the server when we are done client.Disconnect(); ``` -------------------------------- ### Create and Configure a Telepathy Server Source: https://context7.com/mirrornetworking/telepathy/llms.txt Instantiate a `Server` with a maximum message size. Configure optional socket properties and hook event handlers before starting the server. The `Tick()` method must be called in the application loop to process incoming messages and events. ```csharp using System; using Telepathy; // Create server allowing messages up to 16 KB Server server = new Server(16 * 1024); // Configure socket options (optional, these are the defaults) server.NoDelay = true; // disable Nagle algorithm for lower latency server.SendTimeout = 5000; // 5-second send timeout (ms) server.ReceiveTimeout = 0; // disabled by default server.SendQueueLimit = 10000; // auto-disconnect if send backlog exceeds this server.ReceiveQueueLimit = 10000; // Hook events — connectionId identifies each client uniquely server.OnConnected = (connectionId, address) => Console.WriteLine($"[+] Client {connectionId} connected from {address}"); server.OnData = (connectionId, message) => { // message ArraySegment is only valid until this callback returns (allocation-free) string text = System.Text.Encoding.UTF8.GetString(message.Array, message.Offset, message.Count); Console.WriteLine($"[>] #{connectionId}: {text}"); // Echo the message back to the same client server.Send(connectionId, message); }; server.OnDisconnected = (connectionId) => Console.WriteLine($"[-] Client {connectionId} disconnected"); // Start listening on port 1337 bool started = server.Start(1337); Console.WriteLine(started ? "Server started" : "Server already active"); // Game/application loop — call Tick every frame to process messages // processLimit prevents spending too long here if messages pile up while (server.Active) { int remaining = server.Tick(100); // process up to 100 messages per frame // remaining > 0 means there are more messages; call Tick again if needed System.Threading.Thread.Sleep(1000 / 60); // ~60 fps } // Shutdown server.Stop(); ``` -------------------------------- ### Run Server and Clients in Same Process Source: https://context7.com/mirrornetworking/telepathy/llms.txt Execute the LoadTest.exe without arguments to run both the server and client components within the same process. This is useful for local testing. ```bash mono LoadTest.exe ``` -------------------------------- ### Run Load Test Clients Source: https://context7.com/mirrornetworking/telepathy/llms.txt Execute the LoadTest.exe to run a specified number of clients connecting to a server on localhost. Ensure the server is running on the specified port. ```bash mono LoadTest.exe client 127.0.0.1 1337 1000 ``` -------------------------------- ### Client(int MaxMessageSize) Source: https://context7.com/mirrornetworking/telepathy/llms.txt Instantiate a Client with the same MaxMessageSize used by the server. Connect/send operations are non-blocking; the connection attempt runs on a background thread. Hook OnConnected, OnData, and OnDisconnected before calling Connect(). ```APIDOC ## Client(int MaxMessageSize) ### Description Instantiate a `Client` with the same `MaxMessageSize` used by the server. Connect/send operations are non-blocking; the connection attempt runs on a background thread. Hook `OnConnected`, `OnData`, and `OnDisconnected` before calling `Connect()`. ### Method `new Client(int MaxMessageSize)` ### Parameters #### Path Parameters - **MaxMessageSize** (int) - Required - The maximum size of messages the client can send or receive. ### Request Example ```csharp using System; using Telepathy; Client client = new Client(16 * 1024); client.NoDelay = true; client.SendTimeout = 5000; client.SendQueueLimit = 10000; client.ReceiveQueueLimit = 10000; client.OnConnected = () => Console.WriteLine("Connected to server"); client.OnData = (message) => { // Safe to read only within this callback Console.WriteLine($"Received {message.Count} bytes: " + BitConverter.ToString(message.Array, message.Offset, message.Count)); }; client.OnDisconnected = () => Console.WriteLine("Disconnected from server"); // Non-blocking; connection happens on a background thread client.Connect("127.0.0.1", 1337); // Check state Console.WriteLine($"Connecting: {client.Connecting}"); Console.WriteLine($"Connected: {client.Connected}"); ``` ``` -------------------------------- ### Configure and connect a Telepathy client Source: https://context7.com/mirrornetworking/telepathy/llms.txt Instantiate a `Client` with a specified `MaxMessageSize` and configure its properties like `NoDelay`, `SendTimeout`, and queue limits. Hook event handlers before calling `Connect()`. ```csharp using System; using Telepathy; Client client = new Client(16 * 1024); client.NoDelay = true; client.SendTimeout = 5000; client.SendQueueLimit = 10000; client.ReceiveQueueLimit = 10000; client.OnConnected = () => Console.WriteLine("Connected to server"); client.OnData = (message) => { // Safe to read only within this callback Console.WriteLine($"Received {message.Count} bytes: " + BitConverter.ToString(message.Array, message.Offset, message.Count)); }; client.OnDisconnected = () => Console.WriteLine("Disconnected from server"); // Non-blocking; connection happens on a background thread client.Connect("127.0.0.1", 1337); // Check state Console.WriteLine($"Connecting: {client.Connecting}"); Console.WriteLine($"Connected: {client.Connected}"); ``` -------------------------------- ### Run Telepathy Load Test Benchmark Source: https://context7.com/mirrornetworking/telepathy/llms.txt Command to run the Telepathy load test project, spawning a server and N clients for performance benchmarking. ```bash cd LoadTest/bin/Debug # Run server only mono LoadTest.exe server 1337 ``` -------------------------------- ### Allocation-Free Integer Serialization with Utils Source: https://context7.com/mirrornetworking/telepathy/llms.txt Low-level helpers for writing and reading 4-byte big-endian integers without heap allocation. Useful for custom framing protocols. ```csharp // Write a 4-byte big-endian header into an existing buffer at offset 10 byte[] buffer = new byte[256]; Telepathy.Utils.IntToBytesBigEndianNonAlloc(42000, buffer, offset: 10); // buffer[10..13] now encodes 42000 in big-endian // Read it back byte[] header = new byte[] { buffer[10], buffer[11], buffer[12], buffer[13] }; int value = Telepathy.Utils.BytesToIntBigEndian(header); Console.WriteLine(value); // 42000 ``` -------------------------------- ### Redirect Log Output with Telepathy.Log Source: https://context7.com/mirrornetworking/telepathy/llms.txt Override static Action delegates (Info, Warning, Error) to route Telepathy diagnostics to custom sinks like Unity's Debug.Log or a file logger. ```csharp // Redirect to Unity Telepathy.Log.Info = UnityEngine.Debug.Log; Telepathy.Log.Warning = UnityEngine.Debug.LogWarning; Telepathy.Log.Error = UnityEngine.Debug.LogError; // Redirect to a file logger var logFile = new System.IO.StreamWriter("telepathy.log", append: true); Telepathy.Log.Info = msg => logFile.WriteLine($"[INFO] {msg}"); Telepathy.Log.Warning = msg => logFile.WriteLine($"[WARN] {msg}"); Telepathy.Log.Error = msg => logFile.WriteLine($"[ERROR] {msg}"); // Silence all output (e.g., in unit tests) Telepathy.Log.Info = _ => {}; Telepathy.Log.Warning = _ => {}; Telepathy.Log.Error = _ => {}; ``` -------------------------------- ### Generic Object Pool for Allocation-Free Reuse Source: https://context7.com/mirrornetworking/telepathy/llms.txt A lightweight stack-based pool for recycling objects, such as byte arrays, to reduce GC pressure. Useful for performance-critical code. ```csharp // Pool of reusable 1 KB byte arrays Pool bufferPool = new Pool(() => new byte[1024]); // Borrow a buffer byte[] buf = bufferPool.Take(); // ... use buf for network I/O ... // Return it when done (no GC pressure) bufferPool.Return(buf); Console.WriteLine($"Pool size: {bufferPool.Count()}"); // 1 ``` -------------------------------- ### Log Source: https://context7.com/mirrornetworking/telepathy/llms.txt Redirects Telepathy log output. By default, logs are written to the console. You can override `Info`, `Warning`, and `Error` delegates to route diagnostics elsewhere. ```APIDOC ## Log — Redirect log output ### Description `Telepathy.Log` exposes three static `Action` delegates: `Info`, `Warning`, and `Error`. By default they write to `Console`. Override them to route Telepathy diagnostics into Unity's `Debug.Log`, a file logger, or any other sink. ### Method `Telepathy.Log.Info`, `Telepathy.Log.Warning`, `Telepathy.Log.Error` ### Request Example ```csharp // Redirect to Unity Telepathy.Log.Info = UnityEngine.Debug.Log; Telepathy.Log.Warning = UnityEngine.Debug.LogWarning; Telepathy.Log.Error = UnityEngine.Debug.LogError; // Redirect to a file logger var logFile = new System.IO.StreamWriter("telepathy.log", append: true); Telepathy.Log.Info = msg => logFile.WriteLine($"[INFO] {msg}"); Telepathy.Log.Warning = msg => logFile.WriteLine($"[WARN] {msg}"); Telepathy.Log.Error = msg => logFile.WriteLine($"[ERROR] {msg}"); // Silence all output (e.g., in unit tests) Telepathy.Log.Info = _ => {}; Telepathy.Log.Warning = _ => {}; Telepathy.Log.Error = _ => {}; ``` ``` -------------------------------- ### Send Data to Server with Client.Send Source: https://context7.com/mirrornetworking/telepathy/llms.txt Enqueues a message on the send pipe without blocking. Returns false if not connected, if the message exceeds MaxMessageSize, or if the send queue limit is reached. ```csharp // Send a structured packet: 1-byte type + UTF-8 body void SendChatMessage(Client client, string text) { byte[] body = System.Text.Encoding.UTF8.GetBytes(text); byte[] packet = new byte[1 + body.Length]; packet[0] = 0x01; // message type: chat Buffer.BlockCopy(body, 0, packet, 1, body.Length); bool ok = client.Send(new ArraySegment(packet)); if (!ok) Console.WriteLine("Send failed: not connected or queue full"); } // Usage SendChatMessage(client, "Hello, world!"); ``` -------------------------------- ### Send Data to a Client with Telepathy Source: https://context7.com/mirrornetworking/telepathy/llms.txt Enqueues a message on the per-connection send pipe without blocking. Returns `false` if the connection is invalid, the message exceeds `MaxMessageSize`, or the send queue limit is reached, which also closes the connection. ```csharp // Broadcast a byte payload to all currently tracked connections // (Server does not expose a connections list directly; track them yourself) HashSet connectedClients = new HashSet(); server.OnConnected = (id, _) => connectedClients.Add(id); server.OnDisconnected = (id) => connectedClients.Remove(id); // Broadcast byte[] payload = new byte[] { 0x01, 0x02, 0x03 }; ArraySegment segment = new ArraySegment(payload); foreach (int id in connectedClients) { bool sent = server.Send(id, segment); if (!sent) Console.WriteLine($"Send to {id} failed (disconnected or queue full)"); } ``` -------------------------------- ### Unity MonoBehaviour for Telepathy Client/Server Source: https://github.com/mirrornetworking/telepathy/blob/master/README.md This script integrates Telepathy into a Unity project. Ensure 'run in Background' is enabled in project settings. It logs events using Unity's Debug.Log and provides GUI buttons for basic client and server control. ```C# using System; using UnityEngine; public class SimpleExample : MonoBehaviour { Telepathy.Client client = new Telepathy.Client(1024); Telepathy.Server server = new Telepathy.Server(1024); void Awake() { // update even if window isn't focused, otherwise we don't receive. Application.runInBackground = true; // use Debug.Log functions for Telepathy so we can see it in the console Telepathy.Logger.Log = Debug.Log; Telepathy.Logger.LogWarning = Debug.LogWarning; Telepathy.Logger.LogError = Debug.LogError; // hook up events client.OnConnected = () => Debug.Log("Client Connected"); client.OnData = (message) => Debug.Log("Client Data: " + BitConverter.ToString(message.Array, message.Offset, message.Count)); client.OnDisconnected = () => Debug.Log("Client Disconnected"); server.OnConnected = (connectionId) => Debug.Log(connectionId + " Connected"); server.OnData = (connectionId, message) => Debug.Log(connectionId + " Data: " + BitConverter.ToString(message.Array, message.Offset, message.Count)); server.OnDisconnected = (connectionId) => Debug.Log(connectionId + " Disconnected"); } void Update() { // client if (client.Connected) { // send message on key press if (Input.GetKeyDown(KeyCode.Space)) client.Send(new ArraySegment(new byte[]{0x1})); } // tick to process messages // (even if not connected so we still process disconnect messages) client.Tick(100); // server if (server.Active) { if (Input.GetKeyDown(KeyCode.Space)) server.Send(0, new ArraySegment(new byte[]{0x2})); } // tick to process messages // (even if not active so we still process disconnect messages) server.Tick(100); } void OnGUI() { // client GUI.enabled = !client.Connected; if (GUI.Button(new Rect(0, 0, 120, 20), "Connect Client")) client.Connect("localhost", 1337); GUI.enabled = client.Connected; if (GUI.Button(new Rect(130, 0, 120, 20), "Disconnect Client")) client.Disconnect(); // server GUI.enabled = !server.Active; if (GUI.Button(new Rect(0, 25, 120, 20), "Start Server")) server.Start(1337); GUI.enabled = server.Active; if (GUI.Button(new Rect(130, 25, 120, 20), "Stop Server")) server.Stop(); GUI.enabled = true; } void OnApplicationQuit() { // the client/server threads won't receive the OnQuit info if we are // running them in the Editor. they would only quit when we press Play // again later. this is fine, but let's shut them down here for consistency client.Disconnect(); server.Stop(); } } ``` -------------------------------- ### Process Incoming Client Events with Client.Tick Source: https://context7.com/mirrornetworking/telepathy/llms.txt Drains up to processLimit events from the client's receive pipe and invokes registered callbacks. Must be called regularly to keep the event flow alive. ```csharp // Unity MonoBehaviour example void Update() { // Process up to 100 network messages per frame client.Tick(100); // Send on spacebar if (Input.GetKeyDown(KeyCode.Space) && client.Connected) { client.Send(new ArraySegment(new byte[] { 0xFF })); } } void OnApplicationQuit() { client.Disconnect(); } ``` -------------------------------- ### Retrieve client IP with Server.GetClientAddress Source: https://context7.com/mirrornetworking/telepathy/llms.txt Obtain the remote IP address of a client using `Server.GetClientAddress`. This is useful for logging or implementing IP-based restrictions. It returns specific strings for errors or disposed connections. ```csharp server.OnConnected = (connectionId, address) => { // address is already provided by OnConnected, but you can also query it later: string ip = server.GetClientAddress(connectionId); Console.WriteLine($"Client {connectionId} IP: {ip}"); // Example: block connections from a specific range if (ip.StartsWith("192.168.")) { Console.WriteLine("Blocking LAN connection attempt"); server.Disconnect(connectionId); } }; ``` -------------------------------- ### Client.Tick Source: https://context7.com/mirrornetworking/telepathy/llms.txt Processes incoming client events, draining up to `processLimit` events from the client's receive pipe and invoking registered callbacks. Must be called regularly to keep the event flow alive. ```APIDOC ## Client.Tick(int processLimit, Func checkEnabled = null) ### Description Processes incoming client events, draining up to `processLimit` events from the client's receive pipe and invoking the registered callbacks. Returns the remaining event count. Must be called regularly (e.g., every Unity `Update()` frame) to keep the event flow alive. ### Method `Client.Tick` ### Parameters #### Path Parameters - **processLimit** (int) - Required - The maximum number of events to process. - **checkEnabled** (Func) - Optional - A function to check if processing should continue. ### Request Example ```csharp // Unity MonoBehaviour example void Update() { // Process up to 100 network messages per frame client.Tick(100); // Send on spacebar if (Input.GetKeyDown(KeyCode.Space) && client.Connected) { client.Send(new ArraySegment(new byte[] { 0xFF })); } } void OnApplicationQuit() { client.Disconnect(); } ``` ``` -------------------------------- ### Pool Source: https://context7.com/mirrornetworking/telepathy/llms.txt A generic object pool for allocation-free reuse of objects, particularly useful for `byte[]` buffers to reduce GC pressure. ```APIDOC ## Pool — Generic object pool for allocation-free reuse ### Description A lightweight stack-based pool used internally by `MagnificentSendPipe` and `MagnificentReceivePipe` to recycle `byte[]` buffers. Can also be used directly in application code to pool any object type that is expensive to allocate. ### Method `Pool` constructor, `Take()`, `Return()`, `Count()` ### Parameters #### Constructor Parameters - **factory** (Func) - Required - A function that creates a new object when the pool is empty. ### Request Example ```csharp // Pool of reusable 1 KB byte arrays Pool bufferPool = new Pool(() => new byte[1024]); // Borrow a buffer byte[] buf = bufferPool.Take(); // ... use buf for network I/O ... // Return it when done (no GC pressure) bufferPool.Return(buf); Console.WriteLine($"Pool size: {bufferPool.Count()}"); // 1 ``` ``` -------------------------------- ### Client.Send Source: https://context7.com/mirrornetworking/telepathy/llms.txt Enqueues a message on the send pipe without blocking. Returns `false` if not connected, if the message exceeds `MaxMessageSize`, or if the send queue limit is reached. ```APIDOC ## Client.Send(ArraySegment message) ### Description Enqueues a message on the send pipe without blocking. Returns `false` if not connected, if the message exceeds `MaxMessageSize`, or if the send queue limit is reached (and auto-disconnects in that case). ### Method `Client.Send` ### Parameters #### Path Parameters - **message** (ArraySegment) - Required - The message to send. ### Request Example ```csharp // Send a structured packet: 1-byte type + UTF-8 body void SendChatMessage(Client client, string text) { byte[] body = System.Text.Encoding.UTF8.GetBytes(text); byte[] packet = new byte[1 + body.Length]; packet[0] = 0x01; // message type: chat Buffer.BlockCopy(body, 0, packet, 1, body.Length); bool ok = client.Send(new ArraySegment(packet)); if (!ok) Console.WriteLine("Send failed: not connected or queue full"); } // Usage SendChatMessage(client, "Hello, world!"); ``` ``` -------------------------------- ### Server.GetClientAddress(int connectionId) Source: https://context7.com/mirrornetworking/telepathy/llms.txt Returns the remote IP address string for the given connection, useful for logging, banning, or geo-filtering. Returns "" if not found, "unknown" on socket errors, and "Disposed" if the connection has already been cleaned up. ```APIDOC ## Server.GetClientAddress(int connectionId) ### Description Returns the remote IP address string for the given connection, useful for logging, banning, or geo-filtering. Returns `""` if not found, `"unknown"` on socket errors, and `"Disposed"` if the connection has already been cleaned up. ### Method `Server.GetClientAddress(int connectionId)` ### Parameters #### Path Parameters - **connectionId** (int) - Required - The ID of the client connection. ### Request Example ```csharp server.OnConnected = (connectionId, address) => { // address is already provided by OnConnected, but you can also query it later: string ip = server.GetClientAddress(connectionId); Console.WriteLine($"Client {connectionId} IP: {ip}"); // Example: block connections from a specific range if (ip.StartsWith("192.168.")) { Console.WriteLine("Blocking LAN connection attempt"); server.Disconnect(connectionId); } }; ``` ``` -------------------------------- ### Increase File Descriptor Limit on macOS Source: https://context7.com/mirrornetworking/telepathy/llms.txt On macOS, if you encounter 'Too many open files' errors, use this command to temporarily increase the file descriptor limit before running the client. ```bash ulimit -n 2048 && mono LoadTest.exe client 127.0.0.1 1337 1000 ``` -------------------------------- ### Server.Send Source: https://context7.com/mirrornetworking/telepathy/llms.txt Enqueues a message on the per-connection send pipe without blocking the caller. Returns false if the connection does not exist, the message exceeds MaxMessageSize, or the send queue limit has been reached. ```APIDOC ## Server.Send(int connectionId, ArraySegment message) ### Description Send data to a specific client. This method enqueues a message on the per-connection send pipe without blocking the caller. It returns `false` if the connection does not exist, the message exceeds `MaxMessageSize`, or the send queue limit has been reached (in which case the connection is also closed for load-balancing). ### Method `Server.Send(int connectionId, ArraySegment message)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **connectionId** (int) - Required - The unique identifier of the client to send the message to. - **message** (ArraySegment) - Required - The message payload to send. ### Request Example ```csharp // Broadcast a byte payload to all currently tracked connections // (Server does not expose a connections list directly; track them yourself) H নিষ্প connectedClients = new HashSet(); server.OnConnected = (id, _) => connectedClients.Add(id); server.OnDisconnected = (id) => connectedClients.Remove(id); // Broadcast byte[] payload = new byte[] { 0x01, 0x02, 0x03 }; ArraySegment segment = new ArraySegment(payload); foreach (int id in connectedClients) { bool sent = server.Send(id, segment); if (!sent) Console.WriteLine($"Send to {id} failed (disconnected or queue full)"); } ``` ### Response #### Success Response (200) Returns `true` if the message was successfully enqueued, `false` otherwise. #### Response Example None ``` -------------------------------- ### Increase Open File Limit (macOS) Source: https://github.com/mirrornetworking/telepathy/blob/master/LoadTest/README.md Increases the maximum number of open files allowed for the current session on macOS to resolve 'Too many open files' errors. ```bash ulimit -n 2048 ``` -------------------------------- ### Kick a client using Server.Disconnect Source: https://context7.com/mirrornetworking/telepathy/llms.txt Use `Server.Disconnect` to close the TCP connection for a specific client. This triggers a `Disconnected` event on the next `Tick()`. ```csharp server.OnData = (connectionId, message) => { string text = System.Text.Encoding.UTF8.GetString( message.Array, message.Offset, message.Count); if (text.Contains("cheat")) { Console.WriteLine($"Kicking client {connectionId} for cheating"); server.Disconnect(connectionId); // returns true if found, false otherwise } }; ``` -------------------------------- ### Process server events with Server.Tick Source: https://context7.com/mirrornetworking/telepathy/llms.txt Use `Server.Tick` to process incoming events from the receive pipe. It can process a specified number of messages and optionally stop processing if a condition is met via the `checkEnabled` delegate. ```csharp // Example: drain all pending messages, but stop if a scene-load flag is raised bool sceneChanging = false; while (server.Active) { // Keep calling Tick until the pipe is empty or scene is changing int remaining; do { remaining = server.Tick(100, () => !sceneChanging); } while (remaining > 0 && !sceneChanging); System.Threading.Thread.Sleep(1); } ``` -------------------------------- ### Utils.IntToBytesBigEndianNonAlloc / Utils.BytesToIntBigEndian Source: https://context7.com/mirrornetworking/telepathy/llms.txt Allocation-free helpers for serializing and deserializing 4-byte big-endian integers. `IntToBytesBigEndianNonAlloc` writes to an existing `byte[]` at a specified offset, while `BytesToIntBigEndian` reads from a `byte[]`. ```APIDOC ## Utils.IntToBytesBigEndianNonAlloc / Utils.BytesToIntBigEndian — Allocation-free integer serialization ### Description Low-level helpers used internally by the framing protocol (4-byte big-endian length prefix). `IntToBytesBigEndianNonAlloc` writes directly into an existing `byte[]` at a given offset with no heap allocation. `BytesToIntBigEndian` reads four bytes and returns an `int`. ### Method `Telepathy.Utils.IntToBytesBigEndianNonAlloc`, `Telepathy.Utils.BytesToIntBigEndian` ### Parameters #### `IntToBytesBigEndianNonAlloc` Parameters - **value** (int) - Required - The integer value to serialize. - **buffer** (byte[]) - Required - The byte array to write to. - **offset** (int) - Required - The offset within the buffer to start writing. #### `BytesToIntBigEndian` Parameters - **bytes** (byte[]) - Required - The byte array containing the 4-byte integer. ### Request Example ```csharp // Write a 4-byte big-endian header into an existing buffer at offset 10 byte[] buffer = new byte[256]; Telepathy.Utils.IntToBytesBigEndianNonAlloc(42000, buffer, offset: 10); // buffer[10..13] now encodes 42000 in big-endian // Read it back byte[] header = new byte[] { buffer[10], buffer[11], buffer[12], buffer[13] }; int value = Telepathy.Utils.BytesToIntBigEndian(header); Console.WriteLine(value); // 42000 ``` ``` -------------------------------- ### Server.Tick(int processLimit, Func checkEnabled = null) Source: https://context7.com/mirrornetworking/telepathy/llms.txt Drains up to processLimit events from the shared receive pipe on the calling thread, invoking the appropriate OnConnected, OnData, or OnDisconnected callback for each. Returns the number of messages still remaining in the pipe so callers can drain fully if desired. The optional checkEnabled delegate lets middleware (e.g., Mirror scene changes) halt processing mid-tick. ```APIDOC ## Server.Tick(int processLimit, Func checkEnabled = null) ### Description Drains up to `processLimit` events from the shared receive pipe on the calling thread, invoking the appropriate `OnConnected`, `OnData`, or `OnDisconnected` callback for each. Returns the number of messages still remaining in the pipe so callers can drain fully if desired. The optional `checkEnabled` delegate lets middleware (e.g., Mirror scene changes) halt processing mid-tick. ### Method `Server.Tick(int processLimit, Func checkEnabled = null)` ### Parameters #### Path Parameters - **processLimit** (int) - Required - The maximum number of events to process in this tick. - **checkEnabled** (Func) - Optional - A delegate that can halt processing mid-tick. ### Request Example ```csharp // Example: drain all pending messages, but stop if a scene-load flag is raised bool sceneChanging = false; while (server.Active) { // Keep calling Tick until the pipe is empty or scene is changing int remaining; do { remaining = server.Tick(100, () => !sceneChanging); } while (remaining > 0 && !sceneChanging); System.Threading.Thread.Sleep(1); } ``` ``` -------------------------------- ### Disconnect from Server with Client.Disconnect Source: https://context7.com/mirrornetworking/telepathy/llms.txt Closes the TCP connection and interrupts background threads. Safe to call even if not yet connected. ```csharp // Graceful shutdown sequence client.Disconnect(); // Drain remaining events (e.g., the Disconnected callback) before exiting int remaining; do { remaining = client.Tick(100); } while (remaining > 0); Console.WriteLine("Shutdown complete"); ``` -------------------------------- ### Client.Disconnect Source: https://context7.com/mirrornetworking/telepathy/llms.txt Closes the TCP connection and interrupts background threads. Pending queued receive events are still processed by subsequent `Tick()` calls. Safe to call even if not yet connected. ```APIDOC ## Client.Disconnect() ### Description Closes the TCP connection and interrupts background threads. Pending queued receive events (including the final `Disconnected` event) are still processed by subsequent `Tick()` calls. Safe to call even if not yet connected (e.g., to abort a pending `Connect()`). ### Method `Client.Disconnect` ### Request Example ```csharp // Graceful shutdown sequence client.Disconnect(); // Drain remaining events (e.g., the Disconnected callback) before exiting int remaining; do { remaining = client.Tick(100); } while (remaining > 0); Console.WriteLine("Shutdown complete"); ``` ``` -------------------------------- ### Server.Disconnect(int connectionId) Source: https://context7.com/mirrornetworking/telepathy/llms.txt Closes the underlying TCP connection for a specific client. The background receive thread detects the closure and enqueues a Disconnected event, which is then dispatched through OnDisconnected on the next Tick(). ```APIDOC ## Server.Disconnect(int connectionId) ### Description Closes the underlying TCP connection for a specific client. The background receive thread detects the closure and enqueues a `Disconnected` event, which is then dispatched through `OnDisconnected` on the next `Tick()`. ### Method `Server.Disconnect(int connectionId)` ### Parameters #### Path Parameters - **connectionId** (int) - Required - The ID of the client connection to disconnect. ### Request Example ```csharp // Kick a client after receiving a banned-word message server.OnData = (connectionId, message) => { string text = System.Text.Encoding.UTF8.GetString( message.Array, message.Offset, message.Count); if (text.Contains("cheat")) { Console.WriteLine($"Kicking client {connectionId} for cheating"); server.Disconnect(connectionId); // returns true if found, false otherwise } }; ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.