revenantx/litenetlib

Lite reliable UDP library for

Little Game Example on Unity

Lite reliable UDP library for

LiteNetLib 1.0 indev

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

BTC:bc1qn3lwhafsp7ka0r5lew0v7r3qnpj62atqju809n

LTC:LTQqo9yjGVWrXahAByqvx9Jo5TaotjDKXJ

ETH:0x78664986894932bD399B1539D9F65155D0BF55bd

Discord chat:

OLD BRANCH (and examples) for 0.9.x

Little Game Example on Unity

Documentation

Build

NuGet

Release builds

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 (dual mode)
  • Connection statisitcs
  • Multicasting (for discovering hosts in local network)
  • Unity support
  • 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)

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

Server

Issues

Quick list of the latest Issues we found

nongvantinh

nongvantinh

Icon For Comments1

I'm about to create a fast-paced action game, At the start of a match, client and server sync time and set the match time to 00:00.

Can I use NetPeer.RemoteUtcTime to sync time between server and client to the start of 00:00?

Or do I have to use NtpPacket to do that?

Library version: 0.9.5.2 Framework: [.NET 6, Godot]

OS: [Linux, Windows, Android, iOS]

Inurias

Inurias

Icon For Comments8

I understand that 64 channels is enough for most users, but my game sometimes requires more than 64 channels when a lot is going on (many people shooting etc.) which can result in many replicated entities and more than 64 channels being opened. Unreal Engine supports a default maximum of 2048 actor channels for this reason.

I saw that there is a custom fork by @aienabled that enables more than 64 channels by using a ushort. If possible I want to avoid maintaining a custom fork for this functionality.

It makes sense you don't want to increase the header size for all users. I want to ask if it is possible for users who need this functionality to opt-in to this feature, so that all the users have the 1 byte and 64 channels limit by default but users who need more can increase this limit if needed. This way, only the users that need it will have more than 1 byte.

nongvantinh

nongvantinh

Icon For Comments0

I spend some time trying to understand LiteNetLib library version 0.9.5.1 by experiment it with Godot engine mono version 3.3.2. And want to share my knowledge about this library to help someone get started quickly.

Requiments:

Getting started

  • First open project and click build solution in the top right corner.
  • Open the Main scene and uncheck Server Build
  • Now go to: Project -> Export -> add export preset for your desktop and click Export Project
  • Return to the editor and check Server Build then click Play or F5
  • After the server has been running, open your client build and run it.

Results:

  1. client connect to server.zip
  • This example provider-client/server model.
  • On application start, client connect to the server and the server print out a message when the client is trying to connect to.
  1. server accept client and send client a message.zip
  • This example give you basic writing and reading using LiteNetLib.
  1. Server send client serializable packet.zip
  • This example show you the way LiteNetLib serialize packets.
  • On connected, Server send a snapshot packet to client.
  • On client side, whenever client press "space" key it send a "ClientInputMessage" to server to demonstrate sending message from client side.
  1. Test memory leak.zip
  • In the past, I tried yojimbo library (C# version, not C++), and it causes memory leak, This test make sure lite net lib pass the test about memory leak.

Remark:

  • There is another way to serialize packet, by define your own static Serialize/Deserialize function, and send by using method 2, but I see it redundant, so I leave it alone.
  • You can only use one method in 3 ways that I give above to serialize your packet.
  • For games, method 3 is definitely the way to go.

I will add more example usage by adding more future base on the original project I give above.

kkjamie

kkjamie

Icon For Comments2

Have you considered distributing unity releases via https://openupm.com?

This way it's much easier to maintain inside unity projects via the package manager. It's minimal effort I believe, I think they have a CI for automated releases from github, so once it's setup it should be able to detect new releases automatically I think the directory structure may need to be tweaked though. I realise it's not just a unity library of course.

Bradsama

Bradsama

Icon For Comments4

So my script is identical to setting up a client to connect to a Nat Punch server. But each time I start the project with the script attached to a gameobject I keep getting this error.

[S]System.Net.Sockets.SocketException (0x80004005): The system detected an invalid pointer address in attempting to use a pointer argument in a call.

UnityEngine.Debug:Log (object) LiteNetLib.NetDebug:WriteLogic (LiteNetLib.NetLogLevel,string,object[]) (at Assets/LiteNetLib/NetDebug.cs:51) LiteNetLib.NetDebug:WriteError (string,object[]) (at Assets/LiteNetLib/NetDebug.cs:89) LiteNetLib.NetSocket:SendTo (byte[],int,int,System.Net.IPEndPoint,System.Net.Sockets.SocketError&) (at Assets/LiteNetLib/NetSocket.cs:507) LiteNetLib.NatPunchModule:Send<LiteNetLib.NatPunchModule/NatIntroduceRequestPacket> (LiteNetLib.NatPunchModule/NatIntroduceRequestPacket,System.Net.IPEndPoint) (at Assets/LiteNetLib/NatPunchModule.cs:116) LiteNetLib.NatPunchModule:SendNatIntroduceRequest (System.Net.IPEndPoint,string) (at Assets/LiteNetLib/NatPunchModule.cs:181) LiteNetLib.NatPunchModule:SendNatIntroduceRequest (string,int,string) (at Assets/LiteNetLib/NatPunchModule.cs:169) NatClient:Start () (at Assets/NatClient.cs:29)

The line it's pointing to is this using my dns host name from duckdns and set to my servers ip.

client.NatPunchModule.SendNatIntroduceRequest("trdm.duckdns.org", 8500, "token1");

Any idea on what to do to get this working?

mirasrael

mirasrael

feature request
Icon For Comments0

As you may know there are bunch of cases where NAT Punch Through doesn't work. So we need to have alternative way to communicate client and server both behind NAT. And only options which seems working in every case is a Socks5 server. So it will be very useful to have such options in the lib.

HiddenMonk

HiddenMonk

Icon For Comments2

Not sure how big of an issue this is, but it seems that the way connections are established is...

Client1 - Send connect request with connectionID generated from tick time. Client2 - Receive connect request, set connectionState to connected, send connect accept with received connectionID Client1 - Receive connect accept, if connectionID is same we set connectionState to connected.

Shouldnt it be more so like how tcp 3 way handshake does it? (Possibly for security reasons such as helping avoid spoofed ip address?)

Client1 - Send connect request with randomly generated long value. Client2 - Receive connect request, send connect accept with received long value as well as send our own randomly generated long value. Client1 - Receive connect accept, if sent long value is same we set connectionState to connected and we send a ConnectAcceptFinal message with received long value. Client2 - Receive connect accept final, if sent long value is same we set connectionState to connected.

Maybe even then just keep connectionID a int that we just increment every new connection?

lzaiats

lzaiats

feature request
Icon For Comments103

I have been testing LiteNetLib, Lidgren-gen3 and Lidgren-old (the one from Google Code) and Lidgren-old is beating the competitors by far... On my test I have 750 clients connected to a single server instance, receiving ~15 reliable msgs/s and ~100 unreliable msgs/s and Lidgren-old can handle all this data perfectly! Using the same "game code" but using Lidgren-gen3 or LiteNetLib the test "fails" between 100 and 120 clients... Maybe I am missing something with LiteNetLib API, so I can achieve better performance... Do you have any idea where I am doing wrong with your Lib? If you need I can share the code :)

  • My test is using my area of interest management layer, so it can efficiently send to clients only data important to them. Only using this technique I was able to achieve 750 clients on a single server :) Every client is also sending ~15 unreliable msgs/s (movement messages)

Thanks and keep the awesome work!

Versions

Quick list of the latest released versions

v0.9.5.2 - Oct 14, 2021

  • Fix offset in SendInternal for fragmented packets
  • Optimize resolve address
  • Optimize NetPacketProcessor hashing
  • Fix generic types registration in NetPacketProcessor
  • Added DisconnectOnUnreachable (now by default false) option to disable auto disconnect if NetworkUnreachable or HostUnreachable errors got

For installation in typical .NET project use nuget package For Unity use sources zip and copy directory LiteNetLib to your project

v0.9.5.1 - May 26, 2021

(changes since 0.9.5)

  • Fixed source compilation in unity

(changes since 0.9.4)

  • Fixed packet double get from pool (changed lockfree to locks like in 0.8 because of ABA problem, but in a bit better way). This should fix some strange crashes
  • Added manual mode without threads for single-threaded servers
  • Added [IgnoreDataMember] attribute to NetSerializer
  • Added SetPosition to NetDataWriter
  • Added MTU override option
  • Major performance optimization when using multiple channels (#411)
  • Better internal packet recycling (less gc trash)
  • Increased default MTU to 1024 (from 576)
  • Moved NTP code to NetManager
  • Optimized receiving speed (1 copy less)
  • Fix MTU size when layer enabled
  • Fix LastProperty check
  • Fix merged packets verification

For installation in typical .NET project use nuget package For Unity use sources zip and copy directory LiteNetLib to your project

v0.9.5 - May 19, 2021

  • Fixed packet double get from pool (changed lockfree to locks like in 0.8 because of ABA problem, but in a bit better way). This should fix some strange crashes
  • Added manual mode without threads for single-threaded servers
  • Added [IgnoreDataMember] attribute to NetSerializer
  • Added SetPosition to NetDataWriter
  • Added MTU override option
  • Major performance optimization when using multiple channels (#411)
  • Better internal packet recycling (less gc trash)
  • Increased default MTU to 1024 (from 576)
  • Moved NTP code to NetManager
  • Optimized receiving speed (1 copy less)
  • Fix MTU size when layer enabled
  • Fix LastProperty check
  • Fix merged packets verification

For installation in typical .NET project use nuget package For Unity use sources zip and copy directory LiteNetLib to your project

v0.9.4 - Dec 02, 2020

  • Optimize CRC calculating
  • Added UnsyncedReceiveEvent for making only NetworkReceiveEvent unsynced, while other events called from PollEvents
  • Optimized packet pool to lock-free structure
  • Optimized net events pool to lock-free structure
  • Modified PacketLayerBase so that ProcessInboundPacket and ProcessOutboundPacket are both given the IPEndPoint of the sender/receiver, which is necessary for encryption layers that require per-connection state.
  • Made NetStatistics thread-safe using Interlocked, PacketLoss is now monotonically increasing (previously, NetManager.Statistics.PacketLoss would drop if a NetPeer was removed).
  • Flush method of NetManager replaced by NetManager.TriggerUpdate() which works asynchronously.
  • Fixed list of structs serialization
  • Some other fixes and optimizations

v0.9.3.2 - Aug 08, 2020

(changes since 0.9.3.1)

  • Fix serializing of List<T> when you register them with static Read/Write methods (#390)

(changes since 0.9.3)

  • Fix possible infinite(or very long) loop on high-load in PollEvents()

(changes since 0.9.2.2)

  • Protocol increased to 11
  • Added support of List<T> for NetSerializer/NetPacketProcessor for custom types (nested types from wiki)
  • Fixed unsynced connect (#369)
  • Added dual mode for IPv6 (one socket used for IPv4 and IPv6 - so you get less "receive" threads, but this doesn't tested on any platforms except Win/Linux)
  • Improved hole punching code
  • Fixed simultaneous P2P connection (you will get disconnect from one side with DisconnecReason.PeerToPeerConnection) (#374, #366)
  • Improved Unity iOS reconnect hack (#382)
  • Added fix for Nintendo Switch
  • Moved contents of NetExceptions.cs to NetDebug.cs so NetExceptions.cs is deleted

v0.9.3.1 - Aug 03, 2020

(changes since 0.9.3)

  • Fix possible infinite(or very long) loop on high-load in PollEvents()

(changes since 0.9.2.2)

  • Protocol increased to 11
  • Added support of List<T> for NetSerializer/NetPacketProcessor for custom types (nested types from wiki)
  • Fixed unsynced connect (#369)
  • Added dual mode for IPv6 (one socket used for IPv4 and IPv6 - so you get less "receive" threads, but this doesn't tested on any platforms except Win/Linux)
  • Improved hole punching code
  • Fixed simultaneous P2P connection (you will get disconnect from one side with DisconnecReason.PeerToPeerConnection) (#374, #366)
  • Improved Unity iOS reconnect hack (#382)
  • Added fix for Nintendo Switch
  • Moved contents of NetExceptions.cs to NetDebug.cs so NetExceptions.cs is deleted

v0.9.3 - Aug 02, 2020

  • Protocol increased to 11
  • Added support of List<T> for NetSerializer/NetPacketProcessor for custom types (nested types from wiki)
  • Fixed unsynced connect (#369)
  • Added dual mode for IPv6 (one socket used for IPv4 and IPv6 - so you get less "receive" threads, but this doesn't tested on any platforms except Win/Linux)
  • Improved hole punching code
  • Fixed simultaneous P2P connection (you will get disconnect from one side with DisconnecReason.PeerToPeerConnection) (#374, #366)
  • Improved Unity iOS reconnect hack (#382)
  • Added fix for Nintendo Switch
  • Moved contents of NetExceptions.cs to NetDebug.cs so NetExceptions.cs is deleted

v0.9.2.2 - May 11, 2020

(changes since 0.9.2.1)

  • Fixed timing calculations on heavy load
  • Drastically improved speed of NetDataWriter/NetDataReader array methods

(changes since 0.9.2)

  • Fixed unreliable channel crash

(changes since 0.8.3)

  • Added multiple channels for Reliable and Sequenced methods (64 for each type of message) (configured by NetManager.ChannelsCount)
  • Added IPv6Enabled, StatsEnabled to NetManager - to allow enable/disable this features without recompiling and defines (IPV6_ENABLED, STATS_ENABLED)
  • Added packet layers that allows encrypt data or check checksums (Crc32C SSE optimized and XOR already included)
  • Added feature that allows trigger callback on reliable packets when packet delivered (#248)
  • Added RejectForce to reject connection requests without "reliable disconnect" (very handy in DDOS case)
  • Fixed some disconnection cases
  • Fixed ReliableSequenced channel
  • SendDiscoveryRequest renamed to SendBroadcast
  • More informative DisconnectReason in DisconnectInfo
  • Improved connection logic and speed
  • Better packets recycling (less pressure on GC)
  • Added DocFX documentation (https://revenantx.github.io/LiteNetLib/api/index.html)
  • Improved and optimized NetSerializer (~3x faster than previous version)
  • Minimum .netcore version increased to 2.1
  • Fixes for recent Unity3d (2018/2019)
  • Overall optimizations and stability improvements

v0.9.2 - May 03, 2020

(changes since 0.8.3)

  • Added multiple channels for Reliable and Sequenced methods (64 for each type of message) (configured by NetManager.ChannelsCount)
  • Added IPv6Enabled, StatsEnabled to NetManager - to allow enable/disable this features without recompiling and defines (IPV6_ENABLED, STATS_ENABLED)
  • Added packet layers that allows encrypt data or check checksums (Crc32C SSE optimized and XOR already included)
  • Added feature that allows trigger callback on reliable packets when packet delivered (#248)
  • Added RejectForce to reject connection requests without "reliable disconnect" (very handy in DDOS case)
  • Fixed some disconnection cases
  • Fixed ReliableSequenced channel
  • SendDiscoveryRequest renamed to SendBroadcast
  • More informative DisconnectReason in DisconnectInfo
  • Improved connection logic and speed
  • Better packets recycling (less pressure on GC)
  • Added DocFX documentation (https://revenantx.github.io/LiteNetLib/api/index.html)
  • Improved and optimized NetSerializer (~3x faster than previous version)
  • Minimum .netcore version increased to 2.1
  • Fixes for recent Unity3d (2018/2019)
  • Overall optimizations and stability improvements

v0.8.3 - Feb 23, 2019

(differences from 0.7.7.3)

  • Added new NetPacketProcessor for easy serializer usage
  • Added reliable disconnect with user data
  • Added connection requests with user data and OnConnectionRequest on remote side to check incoming data and decide to reject (with reason) or accept incoming peer.
  • Added possibility to bind to specific ip address (IPv4 and IPv6)
  • Added possibility to recycle incoming data (for low GC consumption)
  • Added basic time sync things to NetPeer
  • Improved and enabled merging for all cases (setting removed) (it always reduces traffic)
  • Improved ping logic (more accurate and stable)
  • Changed logging logic
  • Improved connection/disconnection logic
  • Improved speed
  • Updated .netcore and .netstandard requirements to 2.0
  • Unity3d specific fixes
  • Tons of fixes and improvements (which I just forgot)

v0.8.2-beta - Nov 27, 2018

  • Added new NetPacketProcessor for easy serializer usage
  • Added reliable disconnect with user data
  • Added connection requests with user data and OnConnectionRequest on remote side to check incoming data and decide to reject (with reason) or accept incoming peer.
  • Added possibility to bind to specific ip address (IPv4 and IPv6)
  • Added possibility to recycle incoming data (for low GC consumption)
  • Changed logging logic
  • Improved connection/disconnection logic
  • Improved speed
  • Updated .netcore and .netstandard requirements to 2.0
  • Tons of fixes and improvements (which I just forgot)

0.7.7.2 - Jun 14, 2018

  • Fixed .NET core Stop() block,
  • Set disconnected state on disconnected peer
  • Added max string length to NetSerializer constructor

0.7.7.1 - Jan 14, 2018

Hotfix!

  • Fixed reliable channel
  • Fixed socket errors

0.7.7 - Jan 12, 2018

  • Removed unnecessary flow nodes
  • Improved sending speed
  • Thread safe NetPeer.Send and NetManager.PollEvents
  • Packet loss statistics
  • Added NetDataReader clone method.
  • Optimizations

0.7.6.2 - Dec 11, 2017

  • Added Peek method for char
  • Added support for old Unity (4.x)
  • Added NetPeer object as result of NetManager.Connect() method
  • Limit packet pool
  • Fix large memory usage

0.7.6.1 - Oct 09, 2017

  • Hotfixed packet corruption.

0.7.6 - Oct 08, 2017

  • Fix sequenced channel
  • Fixed NetPeer ConnectRequest bug
  • Fix packet leaks
  • Fix Android IL2CPP crash (unity3d related)

0.7.5 - Sep 20, 2017

  • Added bool array support to NetSerializer
  • Improved NetUtils.GetLocalIp method
  • Fixed NetSerializer for UWP
  • Fixed NetDataWriter.PutBytesWithLength
  • Fixed packet loss simulation
  • Fixed "deserialize" method name
  • Fixed packet sizes for unconnected messages

0.6.1fix - Sep 16, 2016

  • Changed IPv4 multicast to broadcast for better compatibility with some platforms
  • Fixed exception at Bind method if multicast or broadcast is not supported.

0.6 - Sep 15, 2016

  • Added multicasting (DiscoveryRequest, DiscoveryResponse)
  • Added connection statistics (bytes/packets received/sent)
  • Better disconnect information and error codes
  • Fixed auto MTU checker
  • Fixes for android IPv6
  • Optimizations.

0.5.3 - Aug 20, 2016

Fixes and optimizations.

0.5.2 - Aug 05, 2016

Fix mtu checker error. Fix NTP request when error received. Minor fixes.

0.5.1 - Jul 28, 2016

Fix bugs introduced in pre-release. Increase socket buffer size to 2mb (you can tune in NetConstants).

0.5 - Jul 27, 2016

Fixed 2 critical bugs (can break connection and drop reliable packets) Always dual mode connection. (IPv4 and IPv6) Optimizations when no flow control. More methods overloads for usability. More information about current state of some classes. Experimental feature UnsyncedEvents. Fixed ReliableResendTime option. Some minor changes.

0.4 - Jun 21, 2016

Minor fixes and optimizations. More support for IPv6 Fix some functions for Unity3d (iOS, Android versions)

0.3 - May 31, 2016

Make threads background. Improve GetLocalIp for some Mono mobile implementations. (iOS, Android) Some thread fixes.

0.2.1 - May 10, 2016

First release

Library Stats (Sep 18, 2022)

Subscribers: 139
Stars: 2.4K
Forks: 429
Issues: 13

CSharpMinifier filters comments and unnecessary whitespace from valid C#

source code in order to arrive at a compressed form without changing the

CSharpMinifier filters comments and unnecessary whitespace from valid C#

csharp-data-visualization

I've always wanted to learn how to visualize data in C#

csharp-data-visualization
GUI

216

SharpMonoInjector

is a tool for injecting assemblies into Mono embedded applications, commonly Unity Engine based games

SharpMonoInjector

CSharp-Collection

Challenges, projects, educational files

CSharp-Collection

CSharp_Veri_Tipleri

byte, sbyte, short, ushort, int, uint, long, ulong, decimal, bool, char, string, var, object veri tipleri incelenmistir

CSharp_Veri_Tipleri

CSharp-CodeSnippet

Wide variety of sample code snippets from the topics related in C#

CSharp-CodeSnippet

csharp-aspnet-microservices

Course on building microservices on

csharp-aspnet-microservices

CSharp &quot;C#&quot; WAVE &quot;

Parses the audio data and the format chunk info from a WAVE-Format audio file &quot;

CSharp &quot;C#&quot; WAVE &quot;

CSharp_ChromaStreamApp

C# Chroma Stream App for Chroma RGB streaming

CSharp_ChromaStreamApp

CSharp-SMTP-Server

Simple (receive only) SMTP server library for C#

CSharp-SMTP-Server