Giter VIP home page Giter VIP logo

litenetlib's People

Contributors

alexr1221 avatar alexstormwood avatar ashoulson avatar ced777ric avatar charanor avatar chrisnobrega avatar cyberandrii avatar firstgeargames avatar forestrf avatar frooxius avatar hguehfuwie avatar hyabean avatar jasperciti avatar jblai avatar jounim avatar kaladrius2trip avatar marsermd avatar mewiof avatar michalpetryka avatar mitsh avatar moe-baker avatar nventimiglia avatar pnarimani avatar revenantx avatar s-rayleigh avatar sewer56 avatar starburst997 avatar trevordaschoculus avatar xmedeko avatar yacuzo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

litenetlib's Issues

Thread Safty

When messages are received, is it possible that they raised on a background thread ? or are you handling the thread dispatching internally (perhaps from the poll method call)?

The same goes for other INetEventListener events (errors, latency, etc).

Also, when sending messages I saw it noted that I should send messages from a background thread, but it looks like you are putting these messages in a queue and doing that already. Is sending from a background thread still a best practice?

Serializing nested classes

Not sure, if this is bug or design, but following doesnt seem to work:

public class MainClass
{
public SubClass Sub { get; set; }
}

public class SubClass
{
public string Something { get; set; }
}

System.Exception: 'Unknown property type: SubClass'

SocketException when connecting to LocalEndPoint

Hi!
Thanks for great software!
Here is some details:
I'm using Unity 5.6.1f1 and source tag 0.7.3
I've slightly modified Unity sample GameClient:

    void Start ()
    {
        _netClient = new NetManager(this, "sample_app");
	    _netClient.Start();
	    _netClient.UpdateTime = 15;
        StartCoroutine(SearchLocalEndPoint());
    }

    IEnumerator SearchLocalEndPoint()
    {
        yield return new WaitForSecondsRealtime(0.1f);
        _netClient.Connect(GetComponent<GameServer>()._netServer.LocalEndPoint);
        yield return null;
    }

and got this:

[S]System.Net.Sockets.SocketException: The requested address is not valid in its context.

  at System.Net.Sockets.Socket.SendTo_nochecks (System.Byte[] buffer, Int32 offset, Int32 size, SocketFlags flags, System.Net.EndPoint remote_end) [0x00000] in <filename unknown>:0 
  at System.Net.Sockets.Socket.SendTo (System.Byte[] buffer, Int32 offset, Int32 size, SocketFlags flags, System.Net.EndPoint remote_end) [0x00000] in <filename unknown>:0 
  at LiteNetLib.NetSocket.SendTo (System.Byte[] data, Int32 offset, Int32 size, LiteNetLib.NetEndPoint remoteEndPoint, System.Int32& errorCode) [0x0008a] in C:\projects\azur\LiteNetLibSampleUnity\Assets\LiteNetLib\NetSocket.cs:225 
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:LogFormat(LogType, String, Object[])
UnityEngine.Debug:LogFormat(String, Object[])
LiteNetLib.NetUtils:DebugWriteLogic(ConsoleColor, String, Object[]) (at Assets\LiteNetLib\NetUtils.cs:151)
LiteNetLib.NetUtils:DebugWriteError(String, Object[]) (at Assets\LiteNetLib\NetUtils.cs:188)
LiteNetLib.NetSocket:SendTo(Byte[], Int32, Int32, NetEndPoint, Int32&) (at Assets\LiteNetLib\NetSocket.cs:235)
LiteNetLib.NetManager:SendRaw(Byte[], Int32, Int32, NetEndPoint) (at Assets\LiteNetLib\NetManager.cs:223)
LiteNetLib.NetManager:SendRawAndRecycle(NetPacket, NetEndPoint) (at Assets\LiteNetLib\NetManager.cs:212)
LiteNetLib.NetPeer:SendConnectRequest() (at Assets\LiteNetLib\NetPeer.cs:194)
LiteNetLib.NetPeer:.ctor(NetManager, NetEndPoint, Int64) (at Assets\LiteNetLib\NetPeer.cs:168)
LiteNetLib.NetManager:Connect(NetEndPoint) (at Assets\LiteNetLib\NetManager.cs:901)
<SearchLocalEndPoint>c__Iterator0:MoveNext() (at Assets\GameClient.cs:28)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr) (at C:\buildslave\unity\build\Runtime\Export\Coroutines.cs:17)
 
(Filename: Assets/LiteNetLib/NetUtils.cs Line: 151)

[CLIENT] We received error 10049
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
GameClient:OnNetworkError(NetEndPoint, Int32) (at Assets\GameClient.cs:66)
LiteNetLib.NetManager:ProcessEvent(NetEvent) (at Assets\LiteNetLib\NetManager.cs:380)
LiteNetLib.NetManager:PollEvents() (at Assets\LiteNetLib\NetManager.cs:865)
GameClient:Update() (at Assets\GameClient.cs:34)
 
(Filename: Assets/GameClient.cs Line: 66)

[S]System.Net.Sockets.SocketException: The requested address is not valid in its context.

  at System.Net.Sockets.Socket.SendTo_nochecks (System.Byte[] buffer, Int32 offset, Int32 size, SocketFlags flags, System.Net.EndPoint remote_end) [0x00000] in <filename unknown>:0 
  at System.Net.Sockets.Socket.SendTo (System.Byte[] buffer, Int32 offset, Int32 size, SocketFlags flags, System.Net.EndPoint remote_end) [0x00000] in <filename unknown>:0 
  at LiteNetLib.NetSocket.SendTo (System.Byte[] data, Int32 offset, Int32 size, LiteNetLib.NetEndPoint remoteEndPoint, System.Int32& errorCode) [0x0008a] in C:\projects\azur\LiteNetLibSampleUnity\Assets\LiteNetLib\NetSocket.cs:225 
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:LogFormat(LogType, String, Object[])
UnityEngine.Debug:LogFormat(String, Object[])
LiteNetLib.NetUtils:DebugWriteLogic(ConsoleColor, String, Object[]) (at Assets\LiteNetLib\NetUtils.cs:151)
LiteNetLib.NetUtils:DebugWriteError(String, Object[]) (at Assets\LiteNetLib\NetUtils.cs:188)
LiteNetLib.NetSocket:SendTo(Byte[], Int32, Int32, NetEndPoint, Int32&) (at Assets\LiteNetLib\NetSocket.cs:235)
LiteNetLib.NetManager:SendRaw(Byte[], Int32, Int32, NetEndPoint) (at Assets\LiteNetLib\NetManager.cs:223)
LiteNetLib.NetManager:SendRawAndRecycle(NetPacket, NetEndPoint) (at Assets\LiteNetLib\NetManager.cs:212)
LiteNetLib.NetPeer:SendConnectRequest() (at Assets\LiteNetLib\NetPeer.cs:194)
LiteNetLib.NetPeer:Update(Int32) (at Assets\LiteNetLib\NetPeer.cs:742)
LiteNetLib.NetManager:UpdateLogic() (at Assets\LiteNetLib\NetManager.cs:452)
LiteNetLib.NetThread:ThreadLogic() (at Assets\LiteNetLib\NetThread.cs:89)
 
(Filename: Assets/LiteNetLib/NetUtils.cs Line: 151)

[CLIENT] We disconnected because SocketSendError
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
GameClient:OnPeerDisconnected(NetPeer, DisconnectInfo) (at Assets\GameClient.cs:99)
LiteNetLib.NetManager:ProcessEvent(NetEvent) (at Assets\LiteNetLib\NetManager.cs:365)
LiteNetLib.NetManager:PollEvents() (at Assets\LiteNetLib\NetManager.cs:865)
GameClient:Update() (at Assets\GameClient.cs:34)
 
(Filename: Assets/GameClient.cs Line: 99)

[CLIENT] We received error 10049
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
GameClient:OnNetworkError(NetEndPoint, Int32) (at Assets\GameClient.cs:66)
LiteNetLib.NetManager:ProcessEvent(NetEvent) (at Assets\LiteNetLib\NetManager.cs:380)
LiteNetLib.NetManager:PollEvents() (at Assets\LiteNetLib\NetManager.cs:865)
GameClient:Update() (at Assets\GameClient.cs:34)
 
(Filename: Assets/GameClient.cs Line: 66)

Documentation

I`m going through the code and one thing that is lacking is comments. A simple three slash (summary) comment on the head of public methods and classes would go a long way.

Maybe we could start with the interfaces?

Take INetEventListener : Super important... Yet, I can only guess at what OnNetworkReceiveUnconnected is or about any of the implementation details behind it.

Latency simulation

Thank you for your work done.
Replaced Lidgren on your creation.
I noticed that the latency simulation and packet loss does not work, also have not found its realization, maybe it's my fault?

Encryption for packets

Does LiteNetLib support encrypting packets? I love your library, but need to have the data encrypted on the wire.

S2S Communication

There is no way to create a connection between the servers. Alternatively, i can use a separate client on the server side, but it would mean the allocation of the new open port. Do you think this is a good solution ?
NetClient сontains a realization of P2P why not do the same for NetServer ?

p2p чат

привет уважаемый автор! в универе для учебных целей есть задача сделать п2п чат лишь на двоих, но никакими станами и т.д. не могу справится с публичными динамическими адресами типа билайн, рт и т.д. Также пробовал вашу либу тоже не удалось( подскажите предназначена ли она для обхода таких вот глабальных натов, если нет то что посоветуете?

SendNatIntroduceRequest() request fails because GetLocalIp() in NetUtils.cs returns a private local ip of range 169.254.xxx.xxx in case of multiple NICs

Hi

Bug Description:
When there are multiple Network interfaces (WIFI and vmware network interfaces ), the SendNatIntroduceRequest() sends the incorrect Local IP to the server resulting in SendNatIntroduceRequest() never succeeding.

Scenario detail:
The problem is only produced when:

  1. You separate out the Server component and client component into separate console apps from the provided sample in **HolePunchServerTest.cs
    HolePunchServerTest.txt
    **
  2. You have multiple interfaces (when you have Vmware installed along with a WIFI adapter connected to the internet) on your client machine A and B
  3. You run the client console app (based on the code from HolePunchServerTest.cs) on Client machine A and client Machine B
  4. Your client machines A and B are both located on the same network and both are connected to the internet via their wireless network adapters.
  5. Both have multiple virtual network adapters (in my case they exist because of VMWARE) but the situation can exist because of any 3rd party VPN software.
  6. You run the server component on a machine on a (potentially) different network with a public IP address and an open/forwarded port (preferably on a different network than the client machines' network so that HOLD punching can be properly tested).

What really happens?

  1. The GetLocalIp() method in NetUtils.cs class will return a private local ip address i.e 169.254.xxx.xxx while the correct IP on your WIFI card would be something like 192.168.xxx.xxx
  2. The call _c1.NatPunchModule.SendNatIntroduceRequest(new NetEndPoint(IpAddress, ServerPort), "token1"); will send that incorrect IP 169.254.xxx.xxx as localEndpoint to the server.
  3. As a result both client machines A and B will report their incorrect local IP Address as 169.254.xxx.xxx , to the server, while their original IP address on their WIFI cards will probably be 192.168.10.3 and 192.168.10.4 (ip address for example case only, actual IPs may be of different range or values depending upon the router/DHCP server they get their IP addresses from)
  4. The server will try to introduce machines with private IP address of range 169.254.xxx.xxx while the clients are necessary not listening on their corresponding local ip addresses.
  5. As a result introduction will fail.

FIX

I fixed the problem by getting all local Ip address using the following piece of code i found somewhere on the internet.

Put this method in Netutils.cs

public static List<string> GetAllLocalIPAddresses(bool preferIPv4 = false)
        {
            return NetworkInterface.GetAllNetworkInterfaces()
                .SelectMany(adapter => adapter.GetIPProperties().UnicastAddresses)
                .Where(adr => adr.Address.AddressFamily == AddressFamily.InterNetwork && adr.IsDnsEligible)
                .Select(adr => adr.Address.ToString()).ToList();
        }

Next step: In NatPunchModule.cs locate the following method:
public void SendNatIntroduceRequest(NetEndPoint masterServerEndPoint, string additionalInfo)
        {
			if (!_netBase.IsRunning)
                return;

            //prepare outgoing data
            NetDataWriter dw = new NetDataWriter();
            var listOfIps = NetUtils.GetAllLocalIPAddresses();
            string networkIp = NetUtils.GetLocalIp(true);
            int networkPort = _netBase.LocalEndPoint.Port;
			
			NetEndPoint localEndPoint = new NetEndPoint(networkIp, networkPort);
			dw.Put(localEndPoint);
			dw.Put(additionalInfo, MaxTokenLength);

			//prepare packet
			var packet = _netBase.PacketPool.GetWithData(PacketProperty.NatIntroductionRequest, dw);
			_netBase.SendRawAndRecycle(packet, masterServerEndPoint);
	}

and replace the code with this method.

New Code:

public void SendNatIntroduceRequest(NetEndPoint masterServerEndPoint, string additionalInfo)
        {
            if (!_netBase.IsRunning)
                return;

            //prepare outgoing data
            NetDataWriter dw = new NetDataWriter();
            var listOfIps = NetUtils.GetAllLocalIPAddresses();
            string networkIp = NetUtils.GetLocalIp(true);
            int networkPort = _netBase.LocalEndPoint.Port;

            foreach (var address in listOfIps)
            {
                //NetEndPoint localEndPoint = new NetEndPoint(networkIp, networkPort);
                NetEndPoint localEndPoint = new NetEndPoint(address, networkPort);
                dw.Put(localEndPoint);
                dw.Put(additionalInfo, MaxTokenLength);

                //prepare packet
                var packet = _netBase.PacketPool.GetWithData(PacketProperty.NatIntroductionRequest, dw);
                _netBase.SendRawAndRecycle(packet, masterServerEndPoint);
            }

        }

Now I know that this is not an ideal solution. However, it gets the job done. The only cost is that it sends all the local ip addresses to the server and the server sends introduction packets to all these local ip addresses which might result in a little bit more traffic.

Maybe the code can be improved and fix is implemented by @RevenantX :)

Looking forward to hearing comments on this.
Regards
TM

P.S I have also attached updated files with my modifications.

NatPunchModule.txt
NetUtils.txt

NAT holepunch client example?

Hi RevenantX, do you happen to have a NAT holepunch connection example?

I see there's a HolePunchServerTest.cs sample, and NatPunchModule.cs, but do you have any examples of a "HolePunchClientTest" at all?

Why the local IP is “169.254.68.213”

Press ESC to quit
Wait peer created. i(169.254.68.213:58084) e([::1]:58084)
Wait peer found, sending introduction...
host - i(169.254.68.213:58084) e([::1]:58084)
client - i(169.254.68.213:58085) e([::1]:58085)
Success C1. Connecting to C2: [::1]:58085
Success C2. Connecting to C1: [::1]:58084
PeerConnected: [::1]:58084
PeerConnected: [::1]:58085

Can't convert string back to NetPeer

Trying to send a whole NetPeer as a string using .ToString() command for convenience purposes works properly, but there's no way to actually convert back the string to a NetPeer as it once was.

What are the current options to convert a NetPeer as a string and then back to NetPeer?

Multiple Connections

I am writing a benchmark / stress tester. I'm currently running into an issue that I can not connect more than two clients at a time. My test is based off of the Echo test.

https://gist.github.com/NVentimiglia/0cec23e985c12d0166043c44585bacdd

That said, here are my initial results with two clients

[0] CON 2 MSG 1896 TIME 15.0026217 OPS 126.377911668599 LAG NA ERR 0
[0] CON 2 MSG 1894 TIME 15.0036247 OPS 126.236162118878 LAG 15 ERR 0
[0] CON 2 MSG 3805 TIME 30.0080228 OPS 126.799423786095 LAG NA ERR 0
[0] CON 2 MSG 3805 TIME 30.0080228 OPS 126.799423786095 LAG 15 ERR 0

Install instructions

Please, add install instructions in the Readme.
I'm trying to figure out how to use it in Unity, but can't understand your sample ;x
can you help me with?

iOS Exceptions/Crashes

Hi, I'm using LiteNetLib in a project but I'm having a few issue with iOS support.

Unity 5.6.0 IL2CPP
Various iOS devices

On the demo, on an older device (iPad Mini 1) I'm getting:
SocketException: Not enough buffer space is available
at System.Net.Sockets.Socket.SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, Int32 optionValue) [0x00000] in :0
at System.Net.Sockets.Socket.set_ReceiveBufferSize (Int32 value) [0x00000] in :0
at LiteNetLib.NetSocket.Bind (Int32 port) [0x00000] in :0
at LiteNetLib.NetManager.Start (Int32 port) [0x00000] in :0
at GameClient.Start () [0x00000] in :0

If I use a newer device (iPhone 7) or change SocketBufferSize in NetConstants, I get a crash:
screen shot 2017-06-20 at 11 13 43 am

The ping value is inaccurate。

public class NetClient : MonoBehaviour, INetEventListener
{
private NetManager _netClient;
private NetPeer _serverPeer;
private NetDataWriter _dataWriter = new NetDataWriter();
private int now;
private SendOptions _option = SendOptions.Unreliable;

void Start ()
{
    UberDebug.Log("start");
    _netClient = new NetManager(this, "sample_app");
    _netClient.Start();
}


void Update()
{
    _netClient.PollEvents();
    if (_serverPeer == null || _serverPeer.ConnectionState != ConnectionState.Connected)
    {
        _netClient.SendDiscoveryRequest(new byte[] { 1 }, 5000);
    }
}

void OnDestroy()
{
    if (_netClient != null) _netClient.Stop();
}


public void OnPeerConnected(NetPeer peer)
{
    _serverPeer = peer;
    StartCoroutine(GetPing());
}

private IEnumerator GetPing()
{
    for (int i = 0; i < 20; i++)
    {
        yield return new WaitForSeconds(1f);
        now = DateTime.Now.Millisecond;
        _serverPeer.Send(_dataWriter, _option);
    }
  
}

public void OnNetworkReceive(NetPeer peer, NetDataReader reader)
{
    Debug.Log("ping:" + (DateTime.Now.Millisecond - now));// Response time

is 20+ms
Debug.Log("serverPeer ping:" + (_serverPeer .Ping));// ping value is 0ms
}

}

Multicast problem

I tested LiteNetLib using Mono on Archlinux and on Windows 10 - hello world works over internet and locally. Today I gave the program to my friend who has Windows 7 and he gets error everytime there is to NetClient.Start() or NetServer.Start(). Samples don't work either.

He gets this error in these lines in NetSocket.cs:

_udpSocketv4.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(MulticastAddressV4, IPAddress.Any));

https://cdn.discordapp.com/attachments/210107559720386560/225974463064178690/unknown.png

Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
   at System.Net.Sockets.Socket.setMulticastOption(SocketOptionName optionName, MulticastOption MR)
   at System.Net.Sockets.Socket.SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, Object optionValue)
   at LiteNetLib.NetSocket.Bind(Int32 port) in E:\Projects\LiteNetLib\LiteNetLib\NetSocket.cs:line 96
   at LiteNetLib.NetBase.Start(Int32 port) in E:\Projects\LiteNetLib\LiteNetLib\NetBase.cs:line 188
   at Netcode.Server.Listen(Int32 port, Int32 maxConnections) in E:\TEMP\Telegram\NetCodes\NetCode\Server\litenet_server.cs:line 39

He CAN succesfully bind using this C# example code:
https://social.msdn.microsoft.com/Forums/en-US/d9951293-e5b6-4d95-ae81-e0f972d4b18d/cant-bind-a-udp-socket-to-a-port?forum=netfxnetcom

No idea why this line fails for him but his router is very restrictive.

Issue on queue lock

Hi,
I have some problems with lock on queue(s), in particular when library check if queue.Count == 0 (eg. SimpleChannel on SendNextPacket method).
For resolving the issue I've moved the lock before the if statement. It's the correct way? Can you verify?

Plus question: There's some method for flushing the queue manually? Because if I call the client.Stop() method after the Send() method, the packet cannot arrive to destination. For now, in my implementation, I have settet the Update() on NetPeer file public and I call it before every Stop.

Thank you

If two clients in an internal network will produce two hole

private void HandleNatIntroduction(NetDataReader dr)
    {
        // read intro
        byte hostByte = dr.GetByte();
        NetEndPoint remoteInternal = dr.GetNetEndPoint();
        NetEndPoint remoteExternal = dr.GetNetEndPoint();
        string token = dr.GetString(MaxTokenLength);

        NetUtils.DebugWrite(ConsoleColor.Cyan, "[NAT] introduction received; we are designated " + (hostByte == HostByte ? "host" : "client"));
        NetDataWriter writer = new NetDataWriter();

        // send internal punch(the first time)
        writer.Put(hostByte);
        writer.Put(token);
        _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatPunchMessage, writer), remoteInternal);
        NetUtils.DebugWrite(ConsoleColor.Cyan, "[NAT] internal punch sent to " + remoteInternal);

        // send external punch(the second time)
        writer.Reset();
        writer.Put(hostByte);
        writer.Put(token);
        _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatPunchMessage, writer), remoteExternal);
        NetUtils.DebugWrite(ConsoleColor.Cyan, "[NAT] external punch sent to " + remoteExternal);
    }

Identify peer on OnReceive event

I'm changing some of my code to use the NetSerializer.Subscribe event. How can I tell for sure what peer sent the information since the OnReceive for the Subscribe only includes the deserialized struct?

...
_netSerializer.Subscribe(OnSamplePacketReceived);
...
private void OnSamplePacketReceived(SamplePacket samplePacket)
{
// How to determine peer that sent here?
}

If multiple peers are sending, the OnNetworkReceive(...) event is too far removed to reliably determine peer associated with the OnReceive Action. In my situation, I'm receiving a request that expects a response.

Unity3d example cannot execute

SocketException: 使用了与请求的协议不兼容的地址。

System.Net.Sockets.Socket..ctor (AddressFamily family, SocketType type, ProtocolType proto)
LiteNetLib.NetSocket.Bind (Int32 port) (at C:/Files/LiteNetLib/LiteNetLib/NetSocket.cs:112)
LiteNetLib.NetBase.Start (Int32 port) (at C:/Files/LiteNetLib/LiteNetLib/NetBase.cs:188)
LiteNetLib.NetBase.Start () (at C:/Files/LiteNetLib/LiteNetLib/NetBase.cs:173)
GameClient.Start () (at Assets/GameClient.cs:19)

Android - PC connection doesn't seem to work (Unity)

Unity sample works fine when launching two instances on same PC, also works between two android devices. But doesn't seem to work between PC and android despite I've added it to firewall exceptions.
Great work btw! 👍

Possible bug with reliableOrdered and acks

With a server and a client in the same machine, after opening the connection and send some messages it starts sending packets like a madman. I enabled the DEBUG_MESSAGES symbol to see what was happening and it logged this:

[RR]SendAcks        
[RR]Resend: 277        
[R]Recieved data from ::0.0.0.1:25002, result: 11        
[S]Send packet to ::0.0.0.1:25002, result: 11        
[S]Send packet to ::0.0.0.1:59573, result: 204        
[RR]PacketProperty: ReliableOrdered        
[RR]ReliableInOrder duplicate        
[RR]Sended        

[RR]SendAcks        
[R]Recieved data from ::0.0.0.1:25002, result: 204        
[RR]Resend: 321        
[S]Send packet to ::0.0.0.1:25002, result: 11        
[S]Send packet to ::0.0.0.1:59573, result: 39        
[RR]PacketProperty: ReliableOrdered        
[RR]Sended        
[RR]ReliableInOrder duplicate        

[RR]SendAcks        
[RR]Resend: 335        
[R]Recieved data from ::0.0.0.1:25002, result: 39        
[S]Send packet to ::0.0.0.1:25002, result: 11        
[S]Send packet to ::0.0.0.1:59573, result: 6        
[RR]PacketProperty: ReliableOrdered        
[RR]ReliableInOrder duplicate        
[RR]Sended        

[RR]SendAcks        
[R]Recieved data from ::0.0.0.1:25002, result: 6        
[RR]Resend: 355        
[S]Send packet to ::0.0.0.1:25002, result: 11        
[S]Send packet to ::0.0.0.1:59573, result: 11        
[RR]PacketProperty: ReliableOrdered        
[RR]ReliableInOrder duplicate        
[R]Recieved data from ::0.0.0.1:25002, result: 11        
[RR]SendAcks        

[RR]Sended        
[RR]Resend: 205        
[S]Send packet to ::0.0.0.1:25002, result: 11        
[S]Send packet to ::0.0.0.1:59573, result: 204        
[RR]PacketProperty: ReliableOrdered        
[RR]Sended        
[RR]ReliableInOrder duplicate        
[RR]Resend: 151        

[RR]SendAcks        
[R]Recieved data from ::0.0.0.1:25002, result: 204        
[S]Send packet to ::0.0.0.1:59573, result: 39        
[S]Send packet to ::0.0.0.1:25002, result: 11        
[RR]Sended        
[RR]Resend: 142        
[RR]PacketProperty: ReliableOrdered        
[RR]ReliableInOrder duplicate        
[S]Send packet to ::0.0.0.1:59573, result: 6        

[RR]SendAcks        
[R]Recieved data from ::0.0.0.1:25002, result: 39        
[RR]Sended        
[S]Send packet to ::0.0.0.1:25002, result: 11        
[RR]Resend: 120        
[RR]PacketProperty: ReliableOrdered        
[RR]ReliableInOrder duplicate        
[S]Send packet to ::0.0.0.1:59573, result: 11        
[R]Recieved data from ::0.0.0.1:25002, result: 6        

[RR]SendAcks        
[S]Send packet to ::0.0.0.1:25002, result: 11        
[RR]Sended        
[RR]PacketProperty: ReliableOrdered        
[RR]ReliableInOrder duplicate        
[RR]Resend: 109        
[R]Recieved data from ::0.0.0.1:25002, result: 11        

It continues on and on. It happens randomly with a hight probability.

I can help with anything to allow you to replicate it.
Thank you!

Connection improvement

We are trying to use it instead of Lidgren.Network, hoping to have a connection approval mechanism and NetPeer's tag (binding object within the game). Thanks!

Benchmarking

I spent the day testing LiteNetLib, and came up with these results :

Uptime : 1.33 min
Connected : 1
Errors 0
Total Messages : 422
Requests Per Second : 316.45
Latency : 188.87 ms
Mem 20, VMem 192, Threads 19

Additional, when trying to connect any more than 2 clients on my machine, the test failed. Currently this same test over websockets is yielding 700,000 ops with latency of 10ms handling 5000 connections. I feel one of us is doing something very incorrect.

My test includes an initial opening handshake followed by a endless echo of 256 length streams. I am using unreliable transportation.

I cant yield my full code as it is part of a larger transport-agnostic framework, but have included the implementation below. Specifically, I have polling on a tight loop on the server and the client (I did have a yield statement in there, but it was not helping.

Transport level Code : https://gist.github.com/NVentimiglia/2534ab5dac563565887ee2e9b9ebd3dc

If you could either point out something I am doing wrong, or provide a console-app stress test that I can compare against, that would be great.

Thread deadlock while calling NetClient.Stop()

I have found a strange deadlock in NetClient.Stop(), it happens when NetClient.Stop() is called from the "main thread" while the "socket thread" receives a disconnect packet from the server, and since both call CloseConnection(), the call to _threadv4.Join() in NetSocket never finishes because the "socket thread" is locked in the "lock (_connectionCloseLock)" inside CloseConnection.

ReliableOrdered bug

Here should used DateTime. UtcNow . Otherwise, it will cause the time to be calculated incorrectly, and it will not send data again.

if (packetFound)
            {
                currentPacket.TimeStamp = DateTime.Now;
                _peer.SendRawData(currentPacket.Packet);
                NetUtils.DebugWrite("[RR]Sended");
            }

Issues with ReadAllPackets?

This is possibly just an error on my side, but I can't seem to get Packet subscribing and receiving to work. I can send/receive normal data using Reader/Writer, but can't seem get to get serialization,packet subscribing to work.

Server Code
`
netSerializer = new NetSerializer();
netSerializer.Subscribe(OnPongPacketRecieved);

    private void OnPongPacketRecieved(PongPacket pPacket)
    {     
       Console.WriteLine("[Server] RecievedPacket:\n" + pPacket);
    }

    public void NetworkRecieveEvent(NetPeer peer, NetDataReader dataReader)
    {
            Console.WriteLine("[Server] recieved data, processing...");
            netSerializer.ReadAllPackets(reader);

    }

Client Code
public void Update(KeyboardState keyboardState)
{

        if (ConnectionMade)
        {
            clientsPaddle.Update(keyboardState);
            writer.Reset();
            PongPacket packet = new PongPacket();
            packet.PacketID = "Paddle";
            packet.Y = clientsPaddle.Position.Y;         
            clientsPeer.Send(serializer.Serialize(packet), SendOptions.ReliableOrdered);
            Console.WriteLine("Sending Packet to Server" + writer.Data);

        }
        client.PollEvents();
    }

`

Struct
struct PongPacket { public string PacketID { get; set; } public float Y { get; set; } }

Any thoughts? Like I mentioned sending the same data not in a Struct and not serializing it works fine. Maybe I am missing something? Worked pretty closely with the examples.

System.InvalidOperation

NetBase.cs Line 303 rarely tosses StackEmpty but should still consider putting the lock on outside of the count check.

Unity game crash on Android

Hi!

I have a problem when run my game (using Unity engine) on android. My game crashed when build with Scripting Backend IL2CPP, but working on Mono2x.

Enviroment:

  • OS: macOS Sierra 10.12.3
  • Unity 5.5.0f3
  • LiteNetLib: latest commit fd58793

If I disable the code lines on NetSocket.cs (see the sample project in LiteNetUnity.zip), game run without crash:

_udpSocketv4.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, true);
_udpSocketv6.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(MulticastAddressV6));

I don't know what happen when disable it :)

Sorry for my poor English!

Crash when client sends some random message

If client sends some random message and server havent following:
netSerializer.SubscribeReusable<RandomMessage, NetPeer>(OnRandomMessage);
server will crash.
Or is there something I have missed?

I think it is necessary to add an asynchronous heartbeat pack。

Udp hole has time limit.If there is no data transfer for a long time(Generally dozens of seconds), the UDP hole will fail。

And "_lastPacketReceivedStart" Refresh requires the update function to execute。If the phone screen locks the screen, the update function will not execute。Then connection will time out.

I do not have the experience of the network library, so there is no confidence to contribute.。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.