Show / Hide Table of Contents

Class LiteNetManager

Main class for all network operations. Can be used as client and/or server.

Inheritance
object
LiteNetManager
NetManager
Implements
IEnumerable<LiteNetPeer>
IEnumerable
Namespace: LiteNetLib
Assembly: LiteNetLib.dll
Syntax
public class LiteNetManager : IEnumerable<LiteNetPeer>, IEnumerable

Constructors

LiteNetManager(ILiteNetEventListener, PacketLayerBase)

NetManager constructor

Declaration
public LiteNetManager(ILiteNetEventListener listener, PacketLayerBase extraPacketLayer = null)
Parameters
Type Name Description
ILiteNetEventListener listener

Network events listener (also can implement IDeliveryEventListener)

PacketLayerBase extraPacketLayer

Extra processing of packages, like CRC checksum or encryption. All connected NetManagers must have same layer.

Fields

AllowPeerAddressChange

Allows peer change it's ip (lte to wifi, wifi to lte, etc). Use only on server

Declaration
public bool AllowPeerAddressChange
Field Value
Type Description
bool

AutoRecycle

Automatically recycle NetPacketReader after OnReceive event

Declaration
public bool AutoRecycle
Field Value
Type Description
bool

BroadcastReceiveEnabled

Allows receive broadcast packets

Declaration
public bool BroadcastReceiveEnabled
Field Value
Type Description
bool

DisconnectOnUnreachable

Disconnect peers if HostUnreachable or NetworkUnreachable spawned (old behaviour 0.9.x was true)

Declaration
public bool DisconnectOnUnreachable
Field Value
Type Description
bool

DisconnectTimeout

If NetManager doesn't receive any packet from remote peer during this time (in milliseconds) then connection will be closed (including library internal keepalive packets)

Declaration
public int DisconnectTimeout
Field Value
Type Description
int

DontRoute

UDP Only Socket Option Normally IP sockets send packets of data through routers and gateways until they reach the final destination. If the DontRoute flag is set to True, then data will be delivered on the local subnet only.

Declaration
public bool DontRoute
Field Value
Type Description
bool

EnableStatistics

Toggles the collection of network statistics for the instance and all known peers

Declaration
public bool EnableStatistics
Field Value
Type Description
bool

IPv6Enabled

IPv6 support

Declaration
public bool IPv6Enabled
Field Value
Type Description
bool

IPv6Support

Declaration
public static readonly bool IPv6Support
Field Value
Type Description
bool

MaxConnectAttempts

Maximum connection attempts before client stops and call disconnect event.

Declaration
public int MaxConnectAttempts
Field Value
Type Description
int

MtuDiscovery

Automatically discovery mtu starting from. Use at own risk because some routers can break MTU detection and connection in result

Declaration
public bool MtuDiscovery
Field Value
Type Description
bool

MtuOverride

Override MTU for all new peers registered in this NetManager, will ignores MTU Discovery!

Declaration
public int MtuOverride
Field Value
Type Description
int

NatPunchEnabled

Enable nat punch messages

Declaration
public bool NatPunchEnabled
Field Value
Type Description
bool

PacketPoolSize

Maximum packet pool size (increase if you have tons of packets sending)

Declaration
public int PacketPoolSize
Field Value
Type Description
int

PingInterval

Interval for latency detection and checking connection (in milliseconds)

Declaration
public int PingInterval
Field Value
Type Description
int

ReceivePollingTime

Poll timeout in microseconds. Increasing can slightly increase performance in cost of slow NetManager.Stop(Socket.Close)

Declaration
public int ReceivePollingTime
Field Value
Type Description
int

ReconnectDelay

Delay between initial connection attempts (in milliseconds)

Declaration
public int ReconnectDelay
Field Value
Type Description
int

ReuseAddress

Enables socket option "ReuseAddress" for specific purposes

Declaration
public bool ReuseAddress
Field Value
Type Description
bool

SimulateLatency

Simulate latency by holding packets for random time. (Works only in DEBUG builds or when SIMULATE_NETWORK is defined)

Declaration
public bool SimulateLatency
Field Value
Type Description
bool

SimulatePacketLoss

Simulate packet loss by dropping random amount of packets. (Works only in DEBUG builds or when SIMULATE_NETWORK is defined)

Declaration
public bool SimulatePacketLoss
Field Value
Type Description
bool

SimulationMaxLatency

Maximum simulated round-trip latency (in milliseconds). Actual latency applied per direction is half of this value.

Declaration
public int SimulationMaxLatency
Field Value
Type Description
int

SimulationMinLatency

Minimum simulated round-trip latency (in milliseconds). Actual latency applied per direction is half of this value.

Declaration
public int SimulationMinLatency
Field Value
Type Description
int

SimulationPacketLossChance

Chance of packet loss when simulation enabled. value in percents (1 - 100).

Declaration
public int SimulationPacketLossChance
Field Value
Type Description
int

Statistics

Statistics of all connections

Declaration
public readonly NetStatistics Statistics
Field Value
Type Description
NetStatistics

UnconnectedMessagesEnabled

Enable messages receiving without connection. (with SendUnconnectedMessage method)

Declaration
public bool UnconnectedMessagesEnabled
Field Value
Type Description
bool

UnsyncedDeliveryEvent

If true - delivery event will be called from "receive" thread immediately otherwise on PollEvents call

Declaration
public bool UnsyncedDeliveryEvent
Field Value
Type Description
bool

UnsyncedEvents

Events automatically will be called without PollEvents method from another thread

Declaration
public bool UnsyncedEvents
Field Value
Type Description
bool

UnsyncedReceiveEvent

If true - receive event will be called from "receive" thread immediately otherwise on PollEvents call

Declaration
public bool UnsyncedReceiveEvent
Field Value
Type Description
bool

UpdateTime

Library logic update and send period in milliseconds Lowest values in Windows doesn't change much because of Thread.Sleep precision To more frequent sends (or sends tied to your game logic) use TriggerUpdate()

Declaration
public int UpdateTime
Field Value
Type Description
int

UseNativeSockets

Experimental feature mostly for servers. Only for Windows/Linux use direct socket calls for send/receive to drastically increase speed and reduce GC pressure

Declaration
public bool UseNativeSockets
Field Value
Type Description
bool

_headPeer

Declaration
protected volatile LiteNetPeer _headPeer
Field Value
Type Description
LiteNetPeer

_peersLock

Declaration
protected readonly ReaderWriterLockSlim _peersLock
Field Value
Type Description
ReaderWriterLockSlim

_udpSocketv4

Declaration
protected Socket _udpSocketv4
Field Value
Type Description
Socket

Properties

ConnectedPeerList

Returns connected peers list (with internal cached list)

Declaration
public List<LiteNetPeer> ConnectedPeerList { get; }
Property Value
Type Description
List<LiteNetPeer>

ConnectedPeersCount

Returns connected peers count

Declaration
public int ConnectedPeersCount { get; }
Property Value
Type Description
int

ExtraPacketSizeForLayer

Declaration
public int ExtraPacketSizeForLayer { get; }
Property Value
Type Description
int

FirstPeer

First peer. Useful for Client mode

Declaration
public LiteNetPeer FirstPeer { get; }
Property Value
Type Description
LiteNetPeer

IsRunning

Returns true if socket listening and update thread is running

Declaration
public bool IsRunning { get; }
Property Value
Type Description
bool

LocalPort

Local EndPoint (host and port)

Declaration
public int LocalPort { get; }
Property Value
Type Description
int

NatPunchModule

NatPunchModule for NAT hole punching operations

Declaration
public NatPunchModule NatPunchModule { get; }
Property Value
Type Description
NatPunchModule

PoolCount

Declaration
public int PoolCount { get; }
Property Value
Type Description
int

Ttl

Declaration
public short Ttl { get; }
Property Value
Type Description
short

Methods

AddPeerToSet(LiteNetPeer)

Declaration
protected bool AddPeerToSet(LiteNetPeer value)
Parameters
Type Name Description
LiteNetPeer value
Returns
Type Description
bool

Connect(IPEndPoint, NetDataWriter)

Connect to remote host

Declaration
public LiteNetPeer Connect(IPEndPoint target, NetDataWriter connectionData)
Parameters
Type Name Description
IPEndPoint target

Server end point (ip and port)

NetDataWriter connectionData

Additional data for remote peer

Returns
Type Description
LiteNetPeer

New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting

Exceptions
Type Condition
InvalidOperationException

Manager is not running. Call Start()

Connect(IPEndPoint, ReadOnlySpan<byte>)

Connect to remote host

Declaration
public LiteNetPeer Connect(IPEndPoint target, ReadOnlySpan<byte> connectionData)
Parameters
Type Name Description
IPEndPoint target

Server end point (ip and port)

ReadOnlySpan<byte> connectionData

Additional data for remote peer

Returns
Type Description
LiteNetPeer

New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting

Exceptions
Type Condition
InvalidOperationException

Manager is not running. Call Start()

Connect(IPEndPoint, string)

Connect to remote host

Declaration
public LiteNetPeer Connect(IPEndPoint target, string key)
Parameters
Type Name Description
IPEndPoint target

Server end point (ip and port)

string key

Connection key

Returns
Type Description
LiteNetPeer

New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting

Exceptions
Type Condition
InvalidOperationException

Manager is not running. Call Start()

Connect(string, int, NetDataWriter)

Connect to remote host

Declaration
public LiteNetPeer Connect(string address, int port, NetDataWriter connectionData)
Parameters
Type Name Description
string address

Server IP or hostname

int port

Server Port

NetDataWriter connectionData

Additional data for remote peer

Returns
Type Description
LiteNetPeer

New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting

Exceptions
Type Condition
InvalidOperationException

Manager is not running. Call Start()

Connect(string, int, string)

Connect to remote host

Declaration
public LiteNetPeer Connect(string address, int port, string key)
Parameters
Type Name Description
string address

Server IP or hostname

int port

Server Port

string key

Connection key

Returns
Type Description
LiteNetPeer

New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting

Exceptions
Type Condition
InvalidOperationException

Manager is not running. Call Start()

ContainsPeer(LiteNetPeer)

Declaration
protected bool ContainsPeer(LiteNetPeer item)
Parameters
Type Name Description
LiteNetPeer item
Returns
Type Description
bool

CreateIncomingPeer(ConnectionRequest, int)

Declaration
protected virtual LiteNetPeer CreateIncomingPeer(ConnectionRequest request, int id)
Parameters
Type Name Description
ConnectionRequest request
int id
Returns
Type Description
LiteNetPeer

CreateOutgoingPeer(IPEndPoint, int, byte, ReadOnlySpan<byte>)

Declaration
protected virtual LiteNetPeer CreateOutgoingPeer(IPEndPoint remoteEndPoint, int id, byte connectNum, ReadOnlySpan<byte> connectData)
Parameters
Type Name Description
IPEndPoint remoteEndPoint
int id
byte connectNum
ReadOnlySpan<byte> connectData
Returns
Type Description
LiteNetPeer

CreateRejectPeer(IPEndPoint, int)

Declaration
protected virtual LiteNetPeer CreateRejectPeer(IPEndPoint remoteEndPoint, int id)
Parameters
Type Name Description
IPEndPoint remoteEndPoint
int id
Returns
Type Description
LiteNetPeer

DisconnectAll()

Disconnect all peers without any additional data

Declaration
public void DisconnectAll()

DisconnectAll(byte[], int, int)

Disconnect all peers with shutdown message

Declaration
public void DisconnectAll(byte[] data, int start, int count)
Parameters
Type Name Description
byte[] data

Data to send (must be less or equal MTU)

int start

Data start

int count

Data count

DisconnectPeer(LiteNetPeer)

Disconnect peer from server

Declaration
public void DisconnectPeer(LiteNetPeer peer)
Parameters
Type Name Description
LiteNetPeer peer

peer to disconnect

DisconnectPeer(LiteNetPeer, NetDataWriter)

Disconnect peer from server and send additional data (Size must be less or equal MTU - 8)

Declaration
public void DisconnectPeer(LiteNetPeer peer, NetDataWriter writer)
Parameters
Type Name Description
LiteNetPeer peer

peer to disconnect

NetDataWriter writer

additional data

DisconnectPeer(LiteNetPeer, byte[])

Disconnect peer from server and send additional data (Size must be less or equal MTU - 8)

Declaration
public void DisconnectPeer(LiteNetPeer peer, byte[] data)
Parameters
Type Name Description
LiteNetPeer peer

peer to disconnect

byte[] data

additional data

DisconnectPeer(LiteNetPeer, byte[], int, int)

Disconnect peer from server and send additional data (Size must be less or equal MTU - 8)

Declaration
public void DisconnectPeer(LiteNetPeer peer, byte[] data, int start, int count)
Parameters
Type Name Description
LiteNetPeer peer

peer to disconnect

byte[] data

additional data

int start

data start

int count

data length

DisconnectPeerForce(LiteNetPeer)

Immediately disconnect peer from server without additional data

Declaration
public void DisconnectPeerForce(LiteNetPeer peer)
Parameters
Type Name Description
LiteNetPeer peer

peer to disconnect

GetEnumerator()

Declaration
public LiteNetManager.NetPeerEnumerator GetEnumerator()
Returns
Type Description
LiteNetManager.NetPeerEnumerator

GetPeerById(int)

Gets peer by peer id

Declaration
public LiteNetPeer GetPeerById(int id)
Parameters
Type Name Description
int id

id of peer

Returns
Type Description
LiteNetPeer

Peer if peer with id exist, otherwise null

GetPeersCount(ConnectionState)

Return peers count with connection state

Declaration
public int GetPeersCount(ConnectionState peerState)
Parameters
Type Name Description
ConnectionState peerState

peer connection state (you can use as bit flags)

Returns
Type Description
int

peers count

GetPeersNonAlloc(List<LiteNetPeer>, ConnectionState)

Get copy of peers (without allocations)

Declaration
public void GetPeersNonAlloc(List<LiteNetPeer> peers, ConnectionState peerState)
Parameters
Type Name Description
List<LiteNetPeer> peers

List that will contain result

ConnectionState peerState

State of peers

ManualUpdate(float)

Update and send logic. Use this only when NetManager started in manual mode

Declaration
public void ManualUpdate(float elapsedMilliseconds)
Parameters
Type Name Description
float elapsedMilliseconds

elapsed milliseconds since last update call

PollEvents()

Receive" pending events. Call this in game update code In Manual mode it will call also socket Receive (which can be slow)

Declaration
public void PollEvents()

ProcessEvent(NetEvent)

Declaration
protected virtual void ProcessEvent(NetEvent evt)
Parameters
Type Name Description
NetEvent evt

ProcessNtpRequests(float)

Declaration
protected virtual void ProcessNtpRequests(float elapsedMilliseconds)
Parameters
Type Name Description
float elapsedMilliseconds

RemovePeerFromSet(LiteNetPeer)

Declaration
protected bool RemovePeerFromSet(LiteNetPeer peer)
Parameters
Type Name Description
LiteNetPeer peer
Returns
Type Description
bool

SendBroadcast(NetDataWriter, int)

Declaration
public bool SendBroadcast(NetDataWriter writer, int port)
Parameters
Type Name Description
NetDataWriter writer
int port
Returns
Type Description
bool

SendBroadcast(byte[], int)

Declaration
public bool SendBroadcast(byte[] data, int port)
Parameters
Type Name Description
byte[] data
int port
Returns
Type Description
bool

SendBroadcast(byte[], int, int, int)

Declaration
public bool SendBroadcast(byte[] data, int start, int length, int port)
Parameters
Type Name Description
byte[] data
int start
int length
int port
Returns
Type Description
bool

SendToAll(NetDataWriter, DeliveryMethod)

Send data to all connected peers (channel - 0)

Declaration
public void SendToAll(NetDataWriter writer, DeliveryMethod options)
Parameters
Type Name Description
NetDataWriter writer

DataWriter with data

DeliveryMethod options

Send options (reliable, unreliable, etc.)

SendToAll(NetDataWriter, DeliveryMethod, LiteNetPeer)

Send data to all connected peers (channel - 0)

Declaration
public void SendToAll(NetDataWriter writer, DeliveryMethod options, LiteNetPeer excludePeer)
Parameters
Type Name Description
NetDataWriter writer

DataWriter with data

DeliveryMethod options

Send options (reliable, unreliable, etc.)

LiteNetPeer excludePeer

Excluded peer

SendToAll(byte[], DeliveryMethod)

Send data to all connected peers (channel - 0)

Declaration
public void SendToAll(byte[] data, DeliveryMethod options)
Parameters
Type Name Description
byte[] data

Data

DeliveryMethod options

Send options (reliable, unreliable, etc.)

SendToAll(byte[], DeliveryMethod, LiteNetPeer)

Send data to all connected peers (channel - 0)

Declaration
public void SendToAll(byte[] data, DeliveryMethod options, LiteNetPeer excludePeer)
Parameters
Type Name Description
byte[] data

Data

DeliveryMethod options

Send options (reliable, unreliable, etc.)

LiteNetPeer excludePeer

Excluded peer

SendToAll(byte[], int, int, DeliveryMethod)

Send data to all connected peers (channel - 0)

Declaration
public void SendToAll(byte[] data, int start, int length, DeliveryMethod options)
Parameters
Type Name Description
byte[] data

Data

int start

Start of data

int length

Length of data

DeliveryMethod options

Send options (reliable, unreliable, etc.)

SendToAll(byte[], int, int, DeliveryMethod, LiteNetPeer)

Send data to all connected peers

Declaration
public void SendToAll(byte[] data, int start, int length, DeliveryMethod options, LiteNetPeer excludePeer)
Parameters
Type Name Description
byte[] data

Data

int start

Start of data

int length

Length of data

DeliveryMethod options

Send options (reliable, unreliable, etc.)

LiteNetPeer excludePeer

Excluded peer

SendToAll(byte[], int, int, byte, DeliveryMethod)

Send data to all connected peers

Declaration
public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options)
Parameters
Type Name Description
byte[] data

Data

int start

Start of data

int length

Length of data

byte channelNumber

Number of channel (from 0 to channelsCount - 1)

DeliveryMethod options

Send options (reliable, unreliable, etc.)

SendToAll(ReadOnlySpan<byte>, DeliveryMethod)

Send data to all connected peers (channel - 0)

Declaration
public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options)
Parameters
Type Name Description
ReadOnlySpan<byte> data

Data

DeliveryMethod options

Send options (reliable, unreliable, etc.)

SendToAll(ReadOnlySpan<byte>, DeliveryMethod, LiteNetPeer)

Send data to all connected peers (channel - 0)

Declaration
public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options, LiteNetPeer excludePeer)
Parameters
Type Name Description
ReadOnlySpan<byte> data

Data

DeliveryMethod options

Send options (reliable, unreliable, etc.)

LiteNetPeer excludePeer

Excluded peer

SendUnconnectedMessage(NetDataWriter, IPEndPoint)

Send message without connection

Declaration
public bool SendUnconnectedMessage(NetDataWriter writer, IPEndPoint remoteEndPoint)
Parameters
Type Name Description
NetDataWriter writer

Data serializer

IPEndPoint remoteEndPoint

Packet destination

Returns
Type Description
bool

Operation result

SendUnconnectedMessage(NetDataWriter, string, int)

Send message without connection. WARNING This method allocates a new IPEndPoint object and synchronously makes a DNS request. If you're calling this method every frame it will be much faster to just cache the IPEndPoint.

Declaration
public bool SendUnconnectedMessage(NetDataWriter writer, string address, int port)
Parameters
Type Name Description
NetDataWriter writer

Data serializer

string address

Packet destination IP or hostname

int port

Packet destination port

Returns
Type Description
bool

Operation result

SendUnconnectedMessage(byte[], int, int, IPEndPoint)

Send message without connection

Declaration
public bool SendUnconnectedMessage(byte[] message, int start, int length, IPEndPoint remoteEndPoint)
Parameters
Type Name Description
byte[] message

Raw data

int start

data start

int length

data length

IPEndPoint remoteEndPoint

Packet destination

Returns
Type Description
bool

Operation result

SendUnconnectedMessage(byte[], IPEndPoint)

Send message without connection

Declaration
public bool SendUnconnectedMessage(byte[] message, IPEndPoint remoteEndPoint)
Parameters
Type Name Description
byte[] message

Raw data

IPEndPoint remoteEndPoint

Packet destination

Returns
Type Description
bool

Operation result

SendUnconnectedMessage(ReadOnlySpan<byte>, IPEndPoint)

Send message without connection

Declaration
public bool SendUnconnectedMessage(ReadOnlySpan<byte> message, IPEndPoint remoteEndPoint)
Parameters
Type Name Description
ReadOnlySpan<byte> message

Raw data

IPEndPoint remoteEndPoint

Packet destination

Returns
Type Description
bool

Operation result

Start()

Start logic thread and listening on available port

Declaration
public bool Start()
Returns
Type Description
bool

Start(int)

Start logic thread and listening on selected port

Declaration
public bool Start(int port)
Parameters
Type Name Description
int port

port to listen

Returns
Type Description
bool

Start(IPAddress, IPAddress, int)

Start logic thread and listening on selected port

Declaration
public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port)
Parameters
Type Name Description
IPAddress addressIPv4

bind to specific ipv4 address

IPAddress addressIPv6

bind to specific ipv6 address

int port

port to listen

Returns
Type Description
bool

Start(IPAddress, IPAddress, int, bool)

Start logic thread and listening on selected port

Declaration
public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port, bool manualMode)
Parameters
Type Name Description
IPAddress addressIPv4

bind to specific ipv4 address

IPAddress addressIPv6

bind to specific ipv6 address

int port

port to listen

bool manualMode

mode of library

Returns
Type Description
bool

Start(string, string, int)

Start logic thread and listening on selected port

Declaration
public bool Start(string addressIPv4, string addressIPv6, int port)
Parameters
Type Name Description
string addressIPv4

bind to specific ipv4 address

string addressIPv6

bind to specific ipv6 address

int port

port to listen

Returns
Type Description
bool

StartInManualMode(int)

Start in manual mode and listening on selected port In this mode you should use ManualReceive (without PollEvents) for receive packets and ManualUpdate(...) for update and send packets This mode useful mostly for single-threaded servers

Declaration
public bool StartInManualMode(int port)
Parameters
Type Name Description
int port

port to listen

Returns
Type Description
bool

StartInManualMode(IPAddress, IPAddress, int)

Start in manual mode and listening on selected port In this mode you should use ManualReceive (without PollEvents) for receive packets and ManualUpdate(...) for update and send packets This mode useful mostly for single-threaded servers

Declaration
public bool StartInManualMode(IPAddress addressIPv4, IPAddress addressIPv6, int port)
Parameters
Type Name Description
IPAddress addressIPv4

bind to specific ipv4 address

IPAddress addressIPv6

bind to specific ipv6 address

int port

port to listen

Returns
Type Description
bool

StartInManualMode(string, string, int)

Start in manual mode and listening on selected port In this mode you should use ManualReceive (without PollEvents) for receive packets and ManualUpdate(...) for update and send packets This mode useful mostly for single-threaded servers

Declaration
public bool StartInManualMode(string addressIPv4, string addressIPv6, int port)
Parameters
Type Name Description
string addressIPv4

bind to specific ipv4 address

string addressIPv6

bind to specific ipv6 address

int port

port to listen

Returns
Type Description
bool

Stop()

Force closes connection and stop all threads.

Declaration
public void Stop()

Stop(bool)

Force closes connection and stop all threads.

Declaration
public void Stop(bool sendDisconnectMessages)
Parameters
Type Name Description
bool sendDisconnectMessages

Send disconnect messages

TriggerUpdate()

Triggers update and send logic immediately (works asynchronously)

Declaration
public void TriggerUpdate()

TryGetPeerById(int, out LiteNetPeer)

Gets peer by peer id

Declaration
public bool TryGetPeerById(int id, out LiteNetPeer peer)
Parameters
Type Name Description
int id

id of peer

LiteNetPeer peer

resulting peer

Returns
Type Description
bool

True if peer with id exist, otherwise false

Implements

IEnumerable<T>
IEnumerable
In this article
Back to top Generated by DocFX