Convert Figma logo to code with AI

RevenantX logoLiteNetLib

Lite reliable UDP library for Mono and .NET

3,043
494
3,043
7

Top Related Projects

Lidgren Network Library

8,004

Provides an efficient allocation free async/await integration for Unity.

Quick Overview

LiteNetLib is a lightweight, cross-platform, and high-performance networking library for .NET and .NET Core. It provides a simple and efficient way to build networked applications, including multiplayer games, real-time communication tools, and distributed systems.

Pros

  • Cross-Platform: LiteNetLib supports multiple platforms, including Windows, Linux, macOS, and mobile devices, making it a versatile choice for a wide range of projects.
  • High Performance: The library is designed for efficiency, with low latency and high throughput, making it suitable for real-time applications.
  • Simplicity: LiteNetLib offers a straightforward API that abstracts away the complexities of low-level networking, allowing developers to focus on their application logic.
  • Reliability: The library includes features like reliable and unreliable message delivery, connection management, and automatic reconnection, ensuring a robust and stable networking experience.

Cons

  • Limited Documentation: While the project has a README file and some examples, the overall documentation could be more comprehensive, which may make it challenging for new users to get started.
  • Lack of Official Support: LiteNetLib is an open-source project, and while it has an active community, it does not have the same level of official support as some commercial networking libraries.
  • Dependency on .NET: As a .NET-based library, LiteNetLib may not be the best choice for projects that do not use the .NET ecosystem.
  • Potential Performance Overhead: While LiteNetLib is designed for high performance, there may be some overhead compared to lower-level networking libraries, depending on the specific requirements of the project.

Code Examples

Here are a few code examples demonstrating the usage of LiteNetLib:

Establishing a Connection

var client = new NetManager(new MyNetEventListener());
client.Start();
client.Connect("127.0.0.1", 9050, "myAppId");

This code sets up a new NetManager instance, which is the main entry point for the LiteNetLib library. The MyNetEventListener class is a custom implementation of the INetEventListener interface, which handles various networking events. The Start() method initializes the networking subsystem, and the Connect() method establishes a connection to the server.

Sending a Message

var message = new NetDataWriter();
message.Put("Hello, server!");
client.Send(message, DeliveryMethod.ReliableOrdered);

This code creates a new NetDataWriter instance, which is used to serialize the message data. The Put() method is used to add the message content to the writer. Finally, the Send() method is called to transmit the message to the server using the DeliveryMethod.ReliableOrdered option, which ensures reliable and ordered delivery.

Handling Received Messages

public class MyNetEventListener : INetEventListener
{
    public void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod)
    {
        var message = reader.GetString();
        Console.WriteLine($"Received message: {message}");
    }

    // Other event handler methods...
}

This code shows the implementation of the MyNetEventListener class, which handles the OnNetworkReceive event. When a message is received from the network, the GetString() method is used to extract the message content, which is then printed to the console.

Getting Started

To get started with LiteNetLib, follow these steps:

  1. Install the LiteNetLib package using your preferred package manager (e.g., NuGet for .NET projects).
  2. Create a new NetManager instance and configure it with your application-specific settings, such as the event listener and connection parameters.
  3. Start the networking subsystem by calling the Start() method on the NetManager instance.
  4. Establish a connection to the server using the Connect() method.
  5. Implement your application logic, including sending and receiving messages, handling connection events, and managing the network state.
  6. Optionally, configure advanced features like message compression, encryption, or custom serialization, depending on the requirements of your project.

For more detailed instructions and examples, refer

Competitor Comparisons

Lidgren Network Library

Pros of lidgren/lidgren-network-gen3

  • Supports a wider range of transport protocols, including UDP, TCP, and WebSocket.
  • Provides a more comprehensive set of features, such as message compression and encryption.
  • Offers better performance and scalability for larger-scale networked applications.

Cons of lidgren/lidgren-network-gen3

  • Has a steeper learning curve and more complex API compared to LiteNetLib.
  • May have a larger codebase and dependencies, which could increase the project's complexity.
  • Requires more configuration and setup compared to the more lightweight LiteNetLib.

Code Comparison

LiteNetLib:

var client = new NetManager(new BasicNetEventListener());
client.Start();
client.Connect("127.0.0.1", 9050);
client.Send(new NetDataWriter().Put("Hello, server!"), DeliveryMethod.ReliableOrdered);

lidgren/lidgren-network-gen3:

var config = new NetPeerConfiguration("myapp");
var peer = new NetClient(config);
peer.Start();
peer.Connect("127.0.0.1", 9050);
peer.SendMessage(new NetOutgoingMessage().Write("Hello, server!"), NetDeliveryMethod.ReliableOrdered);
8,004

Provides an efficient allocation free async/await integration for Unity.

Pros of UniTask

  • UniTask provides a more comprehensive and feature-rich asynchronous programming experience compared to LiteNetLib, with support for async/await, cancellation, and other advanced features.
  • UniTask is designed to be highly performant, with a focus on reducing memory allocations and improving overall efficiency.
  • UniTask integrates well with Unity's coroutine system, allowing for seamless integration with existing Unity-based projects.

Cons of UniTask

  • UniTask has a larger codebase and more dependencies compared to LiteNetLib, which may result in a larger project footprint.
  • The learning curve for UniTask may be steeper than LiteNetLib, as it provides a more complex and feature-rich API.

Code Comparison

LiteNetLib (Networking):

var server = new NetManager(new BasicNetEventListener());
server.Start();

var client = new NetManager(new BasicNetEventListener());
client.Start();
client.Connect("127.0.0.1", 9050, "MyUniqueName");

UniTask (Asynchronous Programming):

async UniTask DoSomethingAsync()
{
    await UniTask.Delay(TimeSpan.FromSeconds(1));
    Debug.Log("Finished!");
}

// Usage
await DoSomethingAsync();

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

LiteNetLib

Lite reliable UDP library for .NET Standard 2.0 (Mono, .NET Core, .NET Framework)

Made in Ukraine

HighLevel API Part: LiteEntitySystem

Discord chat: Discord

OLD BRANCH (and examples) for 0.9.x

Little Game Example on Unity

Documentation

Build

NuGet NuGet NuGet NuGet

Release builds GitHub (pre-)release

DLL build from master

( Warning! Master branch can be unstable! )

Features

  • Lightweight
    • Small CPU and RAM usage
    • Small packet size overhead ( 1 byte for unreliable, 4 bytes for reliable packets )
  • Simple connection handling
  • Peer to peer connections
  • Helper classes for sending and reading messages
  • Multiple data channels
  • Different send mechanics
    • Reliable with order
    • Reliable without order
    • Reliable sequenced (realiable only last packet)
    • Ordered but unreliable with duplication prevention
    • Simple UDP packets without order and reliability
  • Fast packet serializer (Usage manual)
  • Automatic small packets merging
  • Automatic fragmentation of reliable packets
  • Automatic MTU detection
  • Optional CRC32C checksums
  • UDP NAT hole punching
  • NTP time requests
  • Packet loss and latency simulation
  • IPv6 support (using separate socket for performance)
  • Connection statisitcs
  • Multicasting (for discovering hosts in local network)
  • Unity support
  • Support for .NET8 optimized socket calls (much less gc)
  • Supported platforms:
    • Windows/Mac/Linux (.NET Framework, Mono, .NET Core, .NET Standard)
    • Lumin OS (Magic Leap)
    • Monogame
    • Godot
    • Unity 2018.3 (Desktop platforms, Android, iOS, Switch)

Support developer

"Buy Me A Coffee"

Unity notes!!!

  • Minimal supported Unity is 2018.3. For older Unity versions use 0.9.x library versions
  • Always use library sources instead of precompiled DLL files ( because there are platform specific #ifdefs and workarounds for unity bugs )

Usage samples

Client

EventBasedNetListener listener = new EventBasedNetListener();
NetManager client = new NetManager(listener);
client.Start();
client.Connect("localhost" /* host ip or name */, 9050 /* port */, "SomeConnectionKey" /* text key or NetDataWriter */);
listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod, channel) =>
{
    Console.WriteLine("We got: {0}", dataReader.GetString(100 /* max length of string */));
    dataReader.Recycle();
};

while (!Console.KeyAvailable)
{
    client.PollEvents();
    Thread.Sleep(15);
}

client.Stop();

Server

EventBasedNetListener listener = new EventBasedNetListener();
NetManager server = new NetManager(listener);
server.Start(9050 /* port */);

listener.ConnectionRequestEvent += request =>
{
    if(server.ConnectedPeersCount < 10 /* max connections */)
        request.AcceptIfKey("SomeConnectionKey");
    else
        request.Reject();
};

listener.PeerConnectedEvent += peer =>
{
    Console.WriteLine("We got connection: {0}", peer);  // Show peer ip
    NetDataWriter writer = new NetDataWriter();         // Create writer class
    writer.Put("Hello client!");                        // Put some string
    peer.Send(writer, DeliveryMethod.ReliableOrdered);  // Send with reliability
};

while (!Console.KeyAvailable)
{
    server.PollEvents();
    Thread.Sleep(15);
}
server.Stop();