### Start a New ENet Server Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Demonstrates how to start a new ENet server using the Host class. It binds to a specified port, accepts a maximum number of clients, and enters a loop to process network events like connections, disconnections, and received packets. ```csharp using (Host server = new Host()) { Address address = new Address(); address.Port = port; server.Create(address, maxClients); Event netEvent; while (!Console.KeyAvailable) { bool polled = false; while (!polled) { if (server.CheckEvents(out netEvent) <= 0) { if (server.Service(15, out netEvent) <= 0) break; polled = true; } switch (netEvent.Type) { case EventType.None: break; case EventType.Connect: Console.WriteLine("Client connected - ID: " + netEvent.Peer.ID + ", IP: " + netEvent.Peer.IP); break; case EventType.Disconnect: Console.WriteLine("Client disconnected - ID: " + netEvent.Peer.ID + ", IP: " + netEvent.Peer.IP); break; case EventType.Timeout: Console.WriteLine("Client timeout - ID: " + netEvent.Peer.ID + ", IP: " + netEvent.Peer.IP); break; case EventType.Receive: Console.WriteLine("Packet received from - ID: " + netEvent.Peer.ID + ", IP: " + netEvent.Peer.IP + ", Channel ID: " + netEvent.ChannelID + ", Data length: " + netEvent.Packet.Length); netEvent.Packet.Dispose(); break; } } } server.Flush(); } ``` -------------------------------- ### Start a New ENet Client Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Demonstrates how to start a new ENet client and connect to a server. It creates a Host, sets the server address, and attempts to connect. The client then enters a loop to process network events such as connection status, disconnections, and received packets. ```csharp using (Host client = new Host()) { Address address = new Address(); address.SetHost(ip); address.Port = port; client.Create(); Peer peer = client.Connect(address); Event netEvent; while (!Console.KeyAvailable) { bool polled = false; while (!polled) { if (client.CheckEvents(out netEvent) <= 0) { if (client.Service(15, out netEvent) <= 0) break; polled = true; } switch (netEvent.Type) { case EventType.None: break; case EventType.Connect: Console.WriteLine("Client connected to server"); break; case EventType.Disconnect: Console.WriteLine("Client disconnected from server"); break; case EventType.Timeout: Console.WriteLine("Client connection timeout"); break; case EventType.Receive: Console.WriteLine("Packet received from server - Channel ID: " + netEvent.ChannelID + ", Data length: " + netEvent.Packet.Length); netEvent.Packet.Dispose(); break; } } } client.Flush(); } ``` -------------------------------- ### Initialize and Deinitialize ENet Library Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Initializes the ENet library before use and deinitializes it after completion. These are essential setup and cleanup steps for the library. ```csharp ENet.Library.Initialize(); // ... your network code ... ENet.Library.Deinitialize(); ``` -------------------------------- ### Host Creation and Configuration Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Methods for creating a new network host, managing incoming connections, and configuring network parameters like bandwidth and channel limits. ```APIDOC Host.Create(Address? address, int peerLimit, int channelLimit, uint incomingBandwidth, uint outgoingBandwidth, int bufferSize) - Creates a host for communicating with peers. - Parameters: - address: The address to bind to (optional for listening hosts). - peerLimit: The maximum number of peers the host can manage. - channelLimit: The maximum number of channels per connection. - incomingBandwidth: The maximum incoming bandwidth in bytes per second. - outgoingBandwidth: The maximum outgoing bandwidth in bytes per second. - bufferSize: The socket buffer size for sending and receiving datagrams. - Notes: Bandwidth parameters limit the number of reliable packets in transit. Buffer size affects socket performance. Host.PreventConnections(bool state) - Prevents or allows new incoming connections. - Parameters: - state: If true, prevents new connections; if false, allows them. - Notes: When true, the host becomes invisible to new connection attempts. Host.SetBandwidthLimit(uint incomingBandwidth, uint outgoingBandwidth) - Adjusts the bandwidth limits of a host in bytes per second. - Parameters: - incomingBandwidth: New incoming bandwidth limit. - outgoingBandwidth: New outgoing bandwidth limit. Host.SetChannelLimit(int channelLimit) - Limits the maximum allowed channels for future incoming connections. - Parameters: - channelLimit: The new maximum channel limit. Host.SetMaxDuplicatePeers(ushort number) - Limits the maximum allowed duplicate peers from the same host. - Parameters: - number: The maximum number of duplicate peers allowed (must be at least one). - Notes: Defaults to Library.maxPeers. ``` -------------------------------- ### Integrate Custom Memory Allocator with ENet Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Demonstrates how to initialize ENet using custom memory allocation callbacks. This involves defining functions for allocation, freeing, and handling out-of-memory conditions, then passing them to ENet.Library.Initialize. ```csharp AllocCallback OnMemoryAllocate = (size) => { return Marshal.AllocHGlobal(size); }; FreeCallback OnMemoryFree = (memory) => { Marshal.FreeHGlobal(memory); }; NoMemoryCallback OnNoMemory = () => { throw new OutOfMemoryException(); }; Callbacks callbacks = new Callbacks(OnMemoryAllocate, OnMemoryFree, OnNoMemory); if (ENet.Library.Initialize(callbacks)) Console.WriteLine("ENet successfully initialized using a custom memory allocator"); ``` -------------------------------- ### enet-csharp Library API Reference Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Provides details on constants and methods available in the enet-csharp library. This includes configuration constants and core operational methods for managing the native library and data processing. ```APIDOC Library Constants: - `maxChannelCount`: The maximum possible number of channels. - `maxPeers`: The maximum possible number of peers. - `maxPacketSize`: The maximum size of a packet. - `version`: The current compatibility version relative to the native library. - `Time`: Returns a current local monotonic time in milliseconds. It never resets while the application remains alive. Library Methods: - `Initialize(Callbacks callbacks)` - Initializes the native library. - Parameters: - `callbacks`: Optional. Should be used only with a custom memory allocator. - Description: Should be called before starting the work. - Returns: `true` on success or `false` on failure. - `Deinitialize()` - Deinitializes the native library. - Description: Should be called after the work is done. - `CRC64(IntPtr buffers, int bufferCount)` - Computes a checksum for unmanaged buffers. - Parameters: - `buffers`: A pointer to the unmanaged buffers. - `bufferCount`: The number of buffers to process. - Returns: The computed CRC64 checksum. ``` -------------------------------- ### Create and Send ENet Packet Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Shows how to create a new packet with specified data and send it to a connected peer on a particular channel. This is fundamental for network communication. ```csharp Packet packet = default(Packet); byte[] data = new byte[64]; packet.Create(data); peer.Send(channelID, ref packet); ``` -------------------------------- ### CMake Build Configuration for ENet Source: https://github.com/nxrighthere/enet-csharp/blob/master/Source/Native/CMakeLists.txt Configures the build process for the ENet C library using CMake. It allows setting options for debug functionality, static or shared library creation, and platform-specific linker flags for Windows. ```cmake cmake_minimum_required(VERSION 2.9) project(enet C) set(ENET_DEBUG "0" CACHE BOOL "Enable debug functionality") if (WIN32) set(ENET_EXCLUDE_WINDOWS_H "0" CACHE BOOL "Exclude \"windows.h\" header") endif() set(ENET_STATIC "0" CACHE BOOL "Create a static library") set(ENET_SHARED "0" CACHE BOOL "Create a shared library") if (MSYS OR MINGW) set(CMAKE_C_FLAGS "-static") add_definitions(-DWINVER=0x0601) add_definitions(-D_WIN32_WINNT=0x0601) endif() if (ENET_DEBUG) add_definitions(-DENET_DEBUG) endif() if (ENET_STATIC) add_library(enet_static STATIC enet.c ${SOURCES}) if (NOT UNIX) target_link_libraries(enet_static winmm ws2_32) SET_TARGET_PROPERTIES(enet_static PROPERTIES PREFIX "") endif() endif() if (ENET_SHARED) if (APPLE) SET(CMAKE_OSX_ARCHITECTURES "arm64;x86_64") endif() add_definitions(-DENET_DLL) add_library(enet SHARED enet.c ${SOURCES}) if (NOT UNIX) target_link_libraries(enet winmm ws2_32) SET_TARGET_PROPERTIES(enet PROPERTIES PREFIX "") endif() endif() ``` -------------------------------- ### Event Handling and Connection Management Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Methods for checking for network events, initiating connections, and servicing the host to process network traffic. ```APIDOC Host.CheckEvents(out Event @event) - Checks for any queued events on the host and dispatches one if available. - Returns: > 0 if an event was dispatched, 0 if no events are available, < 0 on failure. Host.Connect(Address address, int channelLimit, uint data) - Initiates a connection to a foreign host. - Parameters: - address: The address of the foreign host. - channelLimit: The number of channels to use for the connection (optional). - data: User-supplied data to send with the connection request (optional). - Returns: A peer representing the foreign host on success, or throws an exception on failure. - Notes: The returned peer is not fully connected until Host.Service() dispatches an EventType.Connect event. Host.Service(int timeout, out Event @event) - Waits for events on the host and shuttles packets between the host and its peers. - Parameters: - timeout: The maximum time in milliseconds to poll for events. A timeout of 0 means non-blocking. - @event: An out parameter to receive the dispatched event. - Returns: 1 if an event was dispatched within the timeout, 0 if no events are available, < 0 on failure. - Notes: Must be called regularly to send/receive packets and avoid latency spikes. Essential for game loops when timeout is 0. ``` -------------------------------- ### ENet C# Peer Ping and Throttle Configuration Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Manages connection monitoring and network traffic control. Ping methods help maintain connection liveness and adjust traffic dynamically, while ConfigureThrottle allows fine-tuning of packet dropping behavior. ```APIDOC Peer.Ping() - Sends a ping request to the peer. ENet automatically pings peers, but this can be used for more frequent checks. Peer.PingInterval(uint interval) - Sets the interval in milliseconds at which ENet will send pings to this peer. - Parameters: - interval: The interval in milliseconds for sending pings. Peer.ConfigureThrottle(uint interval, uint acceleration, uint deceleration, uint threshold) - Configures the throttle parameters for the peer to manage unreliable packet dropping. - Parameters: - interval: The time in milliseconds over which to measure mean round-trip time. - acceleration: The amount to increase throttle probability when RTT is significantly lower than the mean. - deceleration: The amount to decrease throttle probability when RTT is significantly higher than the mean. Set to zero to disable throttling. - threshold: A parameter to reduce packet throttling relative to measured RTT in unstable network environments (e.g., Wi-Fi). - Notes: - Throttle ranges from 0 (no unreliable packets sent) to Library.throttleScale (all unreliable packets sent). - Deceleration set to zero disables throttling. - Default threshold is Library.throttleThreshold. ``` -------------------------------- ### Host Creation and Connection Channel Limits Source: https://github.com/nxrighthere/enet-csharp/blob/master/COMMON-MISTAKES.md Mismatched channel limits between ENet endpoints (host and peer) can prevent packets from being delivered on disabled channels. Ensure consistency when initializing the host and connecting peers. ```APIDOC Host.Create(ENetAddress address, int maxPeers, int channelLimit, uint defaultTimeout) - Creates an ENet host. - channelLimit: The maximum number of channels allowed per peer. Must match on both ends. Peer.Connect(ENetAddress address, int channelCount, uint data) - Connects to a remote host. - channelCount: The number of channels to use for this connection. Must be less than or equal to the host's channelLimit. ``` -------------------------------- ### Callback Configuration Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Functions to set custom callback functions for intercepting raw UDP packets and computing checksums. ```APIDOC Host.SetInterceptCallback(InterceptCallback callback) - Sets the callback to notify when a raw UDP packet is intercepted. - Parameters: - callback: The delegate or function pointer to call. - Notes: Can accept a pointer (IntPtr) to a callback. Host.SetChecksumCallback(ChecksumCallback callback) - Sets the callback to notify when a checksum should be computed. - Parameters: - callback: The delegate or function pointer to call. - Notes: Can accept a pointer (IntPtr) to a callback. ``` -------------------------------- ### Host Class Properties Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Provides access to various runtime statistics and states of the network host. These properties offer insights into connection status, packet throughput, and byte transfer counts. ```APIDOC Host.Dispose() - Destroys the host and releases associated resources. Host.IsSet - Returns a boolean indicating the state of the managed pointer. Host.PeersCount - Returns the current number of connected peers. Host.PacketsSent - Returns the total number of packets sent during the session. Host.PacketsReceived - Returns the total number of packets received during the session. Host.BytesSent - Returns the total number of bytes sent during the session. Host.BytesReceived - Returns the total number of bytes received during the session. ``` -------------------------------- ### Packet Structure and Methods Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Represents a network packet, providing methods for packet management, data access, and creation. It includes functionality for setting custom callbacks and copying packet data. ```APIDOC Packet: Dispose(): Destroys the packet. Should only be called when the packet was obtained from an EventType.Receive event. IsSet: Returns the state of the managed pointer. Data: Returns a managed pointer to the packet data. UserData: Gets or sets user-supplied data associated with the packet. Length: Returns the length of the packet's payload. HasReferences: Checks for references to the packet. SetFreeCallback(PacketFreeCallback callback): Sets a callback to notify when the packet is being destroyed. An IntPtr to a callback can be used instead of a delegate reference. Create(byte[] data, int offset, int length, PacketFlags flags): Creates a packet for sending to a peer. Parameters: data: The byte array containing packet data. offset: The starting point of data within the array. length: The length of the data to include. flags: Multiple packet flags can be specified. A pointer to a native buffer can be used instead of a byte array reference. CopyTo(byte[] destination): Copies the packet's payload to the destination byte array. ``` -------------------------------- ### Event Structure Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Contains information about an ENet event, including its type, associated peer, channel ID, user data, and packet. ```APIDOC Event: Type: Returns the type of the event. Peer: Returns the peer that generated the event (connect, disconnect, receive, timeout). ChannelID: Returns the channel ID on the peer that generated the event, if applicable. Data: Returns the user-supplied data, if applicable. Packet: Returns the packet associated with the event, if applicable. ``` -------------------------------- ### Packet Sending and Broadcasting Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Functions for queuing packets to be sent to specific peers or broadcasting to multiple peers, and for flushing the send queue. ```APIDOC Host.Broadcast(byte channelID, ref Packet packet, Peer[] peers) - Queues a packet to be sent to a range of peers or all peers. - Parameters: - channelID: The channel to send the packet on. - packet: The packet to send. - peers: An array of peers to send to. If null or empty, broadcasts to all peers. Zeroed Peer structures are excluded. Host.Flush() - Sends any queued packets on the specified host to their designated peers. ``` -------------------------------- ### Packet Creation and Payload Size Source: https://github.com/nxrighthere/enet-csharp/blob/master/COMMON-MISTAKES.md High latency with many connections can occur if entire buffers are sent instead of just the payload. Use Packet.Create() with the correct length to optimize packet size and avoid overwhelming ENet with large, reliably fragmented packets. ```csharp // Incorrect: Sending a large buffer that includes unused space. // byte[] largeBuffer = new byte[1024]; // Buffer.BlockCopy(myData, 0, largeBuffer, 0, myData.Length); // Peer.Send(0, ref largeBuffer); // Correct: Create a packet with only the necessary data. // byte[] dataToSend = new byte[myData.Length]; // Buffer.BlockCopy(myData, 0, dataToSend, 0, myData.Length); // Packet packet = Packet.Create(dataToSend, PacketFlags.Reliable); // Peer.Send(0, ref packet); ``` ```APIDOC Packet.Create(byte[] data, PacketFlags flags) - Creates a new packet with the specified data and flags. - data: The byte array containing the packet payload. - flags: PacketFlags to control reliability, fragmentation, etc. - Returns: A new Packet structure. ``` -------------------------------- ### ENet C# Peer Packet Management Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Methods for sending packets to a peer and receiving packets from a peer. These are fundamental operations for network communication within the ENet library. ```APIDOC Peer.Send(byte channelID, ref Packet packet) - Queues a packet to be sent to the peer on the specified channel. - Parameters: - channelID: The ID of the channel to send the packet on. - packet: A reference to the Packet object to be sent. - Returns: True if the packet was successfully queued, false otherwise. Peer.Receive(out byte channelID, out Packet packet) - Attempts to dequeue an incoming queued packet from the peer. - Parameters: - channelID: Output parameter to receive the channel ID of the dequeued packet. - packet: Output parameter to receive the dequeued Packet object. - Returns: True if a packet was dequeued, false if no packets are available. ``` -------------------------------- ### Host Flushing Before Shutdown Source: https://github.com/nxrighthere/enet-csharp/blob/master/COMMON-MISTAKES.md Failure to flush the host before ending a session can result in enqueued packets and protocol commands not being sent. Always ensure the host is flushed to guarantee all data is transmitted. ```csharp // Before shutting down the host: // host.Flush(); ``` ```APIDOC Host.Flush() - Sends all outgoing packets and protocol commands immediately. - Should be called before destroying the host or closing connections to ensure data delivery. ``` -------------------------------- ### Host Callback Delegates Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Callbacks related to host-level events within the ENet library. These handle raw packet interception and checksum computation. ```APIDOC InterceptCallback(ref Event @event, ref Address address, IntPtr receivedData, int receivedDataLength): Notifies when a raw UDP packet is intercepted. The returned status code instructs ENet on event handling: 1: Dispatch event by service. 0: ENet subsystems handle received data. -1: An error occurred. A reference to the delegate must be preserved to prevent garbage collection. ChecksumCallback(IntPtr buffers, int bufferCount): Notifies when a checksum should be computed for buffers during sending and receiving. Returns a 64-bit checksum. ENet automatically handles integrity verification if a checksum mechanism is enabled on both ends. Can be used with ENet.Library.CRC64(). A reference to the delegate must be preserved to prevent garbage collection. ``` -------------------------------- ### Host Event Processing Loop Source: https://github.com/nxrighthere/enet-csharp/blob/master/COMMON-MISTAKES.md A host degrading with many packets or failing to accept multiple connections often means the service loop is not processing enough events per frame. Ensure the service is called within a loop to handle all pending events efficiently. ```csharp // Inefficient: Processing only one event per game loop iteration. // host.Service(0, out ENetEvent event); // Efficient: Process all available events in a loop. // while (host.Service(0, out ENetEvent event) > 0) { // // Process event... // } ``` ```APIDOC Host.Create(ENetAddress address, int maxPeers, int channelLimit, uint defaultTimeout) - Creates an ENet host. - maxPeers: The maximum number of peers the host can connect to. - Consider increasing socket buffer size (e.g., up to 1MB) via OS settings if performance issues persist with many connections. ``` -------------------------------- ### ENet API Reference: PacketFlags Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Defines flags for controlling packet delivery behavior in ENet's Peer.Send() function. These flags specify reliability, sequencing, fragmentation, and sending urgency. ```APIDOC PacketFlags: - None: Unreliable sequenced, delivery not guaranteed. - Reliable: Reliable sequenced, packet must be received and may be resent. - Unsequenced: Packet not sequenced, may be delivered out of order; delivery is unreliable. - NoAllocate: Packet data is not allocated by ENet; user must manage packet lifetime via PacketFreeCallback. - UnreliableFragmented: Unreliable fragmentation if packet exceeds MTU; by default, unreliable packets exceeding MTU are fragmented reliably. Use to keep fragmentation unreliable. - Instant: Packet sent instantly, not bundled with others in the next service iteration; trades multiplexing efficiency for latency. Cannot be used for multiple Peer.Send() calls. - Unthrottled: Unreliable packet enqueued for sending should not be dropped due to throttling and should be sent if possible. - Sent: Packet has been sent from all queues it has entered. ``` -------------------------------- ### ENet C# Peer Properties Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Provides access to various attributes of a connected peer, including its identifier, network address, connection state, and performance metrics. These properties offer insights into the peer's status and the quality of the connection. ```APIDOC Peer.IsSet - Returns a boolean indicating the state of the managed pointer. Peer.ID - Returns the peer ID. This value is always zero on the client side. Peer.IP - Returns the IP address of the peer in a printable string format. Peer.Port - Returns the port number of the peer. Peer.MTU - Returns the Maximum Transmission Unit (MTU) for the connection to the peer. Peer.State - Returns the current state of the peer, described by the PeerState enumeration. Peer.RoundTripTime - Returns the current round-trip time (RTT) to the peer in milliseconds. Peer.LastRoundTripTime - Returns the round-trip time since the last acknowledgment in milliseconds. Peer.LastSendTime - Returns the timestamp of the last packet sent to the peer in milliseconds. Peer.LastReceiveTime - Returns the timestamp of the last packet received from the peer in milliseconds. Peer.PacketsSent - Returns the total number of packets sent to the peer during the connection. Peer.PacketsLost - Returns the total number of packets considered lost during the connection, based on retransmission logic. Peer.PacketsThrottle - Returns a ratio indicating the degree to which packets are being throttled due to connection conditions. Peer.BytesSent - Returns the total number of bytes sent to the peer during the connection. Peer.BytesReceived - Returns the total number of bytes received from the peer during the connection. Peer.Data - Gets or sets user-supplied data associated with the peer. Requires an explicit cast to the appropriate data type. ``` -------------------------------- ### Host.Service() Frequency Source: https://github.com/nxrighthere/enet-csharp/blob/master/COMMON-MISTAKES.md Unstable round-trip times, especially on localhost, often indicate that Host.Service() is not being called frequently enough. Continuous processing of services and events is vital for ENet's packet shuttling. ```csharp // Ensure Host.Service() is called regularly, ideally in a tight loop. // while (true) { // host.Service(0, out ENetEvent event); // // Process event... // } ``` ```APIDOC Host.Service(uint timeout, out ENetEvent event) - Processes ENet events and dispatches packets. - timeout: The maximum time in milliseconds to wait for an event. A value of 0 processes immediately. - Returns: The number of events processed. ``` -------------------------------- ### Copy Payload from ENet Packet Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Illustrates how to copy the raw data payload from a received ENet packet into a byte array buffer. This is useful for processing incoming data. ```csharp byte[] buffer = new byte[1024]; netEvent.Packet.CopyTo(buffer); ``` -------------------------------- ### Peer Disconnection and Timeout Management Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Manages peer connection states, including setting timeout parameters and initiating various disconnection methods. These methods control how and when a peer is disconnected from the network, considering factors like acknowledgment of reliable traffic and queued outgoing packets. ```APIDOC Peer Class Methods: Peer.Timeout(uint timeoutLimit, uint timeoutMinimum, uint timeoutMaximum) Sets timeout parameters for a peer. These parameters control how and when a peer will timeout due to a failure to acknowledge reliable traffic. The values are used in a semi-linear mechanism where timeouts increase until a limit is reached. If at the limit and reliable packets are sent but not acknowledged within a minimum time, the peer disconnects. If not acknowledged within a maximum time, disconnection occurs regardless of the current timeout limit. Parameters: timeoutLimit: The maximum timeout value. timeoutMinimum: The minimum timeout value. timeoutMaximum: The maximum time period for disconnection. Peer.Disconnect(uint data) Requests a graceful disconnection from a peer. Parameters: data: User-defined data associated with the disconnection. Peer.DisconnectNow(uint data) Forces an immediate disconnection from a peer. Parameters: data: User-defined data associated with the disconnection. Peer.DisconnectLater(uint data) Requests a disconnection from a peer, but only after all currently queued outgoing packets have been sent. Parameters: data: User-defined data associated with the disconnection. Peer.Reset() Forcefully disconnects a peer without notifying the foreign host. The foreign host will eventually timeout its connection to the local host. Parameters: None. ``` -------------------------------- ### Address Structure Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Represents a network address, containing host data and port number. It provides methods for IP address manipulation and host resolution. ```APIDOC Address: Port: Gets or sets the port number. GetIP(): Gets the IP address as a string. SetIP(string ip): Sets the IP address. For IPv4 broadcast in the local network, use "255.255.255.255". ENet will broadcast and update the address to the server's actual IP. GetHost(): Attempts a reverse lookup from the address, returning a resolved name or IP address. SetHost(string hostName): Sets the host name or IP address. Should be used for binding to a network interface or connecting to a foreign host. Returns true on success, false on failure. ``` -------------------------------- ### Packet Lifecycle Management Source: https://github.com/nxrighthere/enet-csharp/blob/master/COMMON-MISTAKES.md Proper handling of ENet packets is crucial to avoid memory access failures. Packets are managed by ENet after sending or receiving, and should not be disposed manually by the user unless explicitly created and owned. ```csharp // Incorrect: Disposing a packet after sending // ENet manages packet memory after sending. // Packet.Dispose(); // Avoid this. // Correct: Let ENet manage packet memory after sending. // If you create a packet with Packet.Create(), you are responsible for its disposal. // Packet packet = Packet.Create(data, PacketFlags.Reliable); // peer.Send(0, ref packet); // packet.Dispose(); // Dispose only if you created it and ENet doesn't take ownership. ``` -------------------------------- ### Memory Callback Delegates Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Callbacks related to memory management within the ENet library. These delegates are invoked for memory allocation and deallocation events. ```APIDOC AllocCallback(IntPtr size): Notifies when memory is requested for allocation. Expects a pointer to the newly allocated memory. A reference to the delegate must be preserved to prevent garbage collection. FreeCallback(IntPtr memory): Notifies when memory can be freed. A reference to the delegate must be preserved to prevent garbage collection. NoMemoryCallback(): Notifies when there is insufficient memory. A reference to the delegate must be preserved to prevent garbage collection. ``` -------------------------------- ### PeerState Enum Definitions Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Defines the possible states for a peer connection within the ENet library. These states indicate the current lifecycle of a peer connection. ```APIDOC PeerState: Uninitialized: A peer that has not yet been initialized. Disconnected: A peer that has been disconnected or timed out. Connecting: A peer connection is currently in progress. Connected: A peer has successfully established a connection. Disconnecting: A peer disconnection is currently in progress. Zombie: A peer that was not properly disconnected. ``` -------------------------------- ### Unreliable Packet Throttling with Latency Simulation Source: https://github.com/nxrighthere/enet-csharp/blob/master/COMMON-MISTAKES.md Unreliable packets can be dropped significantly when simulated latency exceeds a threshold, especially if applied mid-process rather than before connection establishment. Configure Peer.ConfigureThrottle() to manage this. ```APIDOC Peer.ConfigureThrottle(uint unknown, uint initial, uint maintenance, uint sampleVariance, uint decline, uint max, uint threshold) - Configures the throttling mechanism for unreliable packets. - threshold: The simulated latency threshold (default 40ms) above which unreliable packets may be throttled. - Tuning these parameters can help manage packet loss under simulated latency conditions. ``` -------------------------------- ### ENet API Reference: EventType Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Defines the types of events that can occur during ENet operations, as reported by Event.Type. These events signal connection status, data reception, and timeouts. ```APIDOC EventType: - None: No event occurred within the specified time limit. - Connect: A connection request initiated by Peer.Connect() has completed. Event.Peer returns the connected peer. Event.Data contains user-supplied connection data or 0. - Disconnect: A peer has disconnected. This event is generated upon successful completion of a disconnect initiated by Peer.Disconnect(). Event.Peer returns the disconnected peer. Event.Data contains user-supplied disconnection data or 0. - Receive: A packet has been received from a peer. Event.Peer returns the sending peer. Event.ChannelID specifies the channel number. Event.Packet returns the received packet, which must be disposed using Event.Packet.Dispose() after use. - Timeout: A peer has timed out. This occurs if a peer times out or if a connection request initialized by Peer.Connect() has timed out. Event.Peer returns the peer that timed out. ``` -------------------------------- ### Packet Callback Delegates Source: https://github.com/nxrighthere/enet-csharp/blob/master/README.md Callbacks related to packet management within the ENet library. These are invoked when packets are being destroyed or acknowledged. ```APIDOC PacketFreeCallback(Packet packet): Notifies when a packet is being destroyed. Indicates if a reliable packet was acknowledged. A reference to the delegate must be preserved to prevent garbage collection. ``` -------------------------------- ### Packet Disposal Duplication Source: https://github.com/nxrighthere/enet-csharp/blob/master/COMMON-MISTAKES.md Calling Dispose on a received ENet packet more than once will lead to memory access failures. As ENet's Packet is a value type, internal checks prevent double disposal, but incorrect handling can still cause crashes. ```csharp // Incorrect: Disposing a received packet multiple times. // Packet receivedPacket = ...; // receivedPacket.Dispose(); // receivedPacket.Dispose(); // This will cause a crash. // Best practice: Ensure a packet is disposed only once, typically after all its uses are exhausted. // If a received packet is sent further, ENet retains ownership and it should not be disposed by the user. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.